Using classes without namespace with Yii2

旧街凉风 提交于 2019-11-29 09:33:45
arogachev

When the class does not have namespace it means it's in the root namespace.

Option 1:

use Twocheckout;

...

Twocheckout::format('json');

Option 2:

\Twocheckout::format('json');

For example, PHPExcel extension also doesn't have namespaces, similar question was answered on official forum.

Related questions:

Importing class without namespace to namespaced class

How to use "root" namespace of php?

Official PHP documentation:

http://php.net/manual/en/language.namespaces.fallback.php

Update:

But PHPExcel has own autoloader, while 2Checkout does not. All classes are included by requiring one main abstract class. It's even mentioned in official readme:

require_once("/path/to/2checkout-php/lib/Twocheckout.php");

So you need to manually include it before using library classes. It can be done with help of alias to avoid writing full path.

use Yii;
...
$path = Yii::getAlias("@vendor/2checkout/2checkout-php/lib/Twocheckout.php");
require_once($path);
$sale = new \Twocheckout_Sale();

For usage in one place it's OK, but if it will be used in many places of application, it's better to require it in entry script index.php:

require(__DIR__ . '/../../vendor/autoload.php');

require(__DIR__ . '/../../vendor/2checkout/2checkout-php/lib/Twocheckout.php');

require(__DIR__ . '/../../vendor/yiisoft/yii2/Yii.php');
require(__DIR__ . '/../../common/config/bootstrap.php');
require(__DIR__ . '/../config/bootstrap.php');

I also recommend to read tips in official documentatiton about using downloaded libraries, there are more options you can use depending on the specific library.

/* Try this  */
public function actionTest(){
    //package
    require(Yii::getAlias('@vendor')."/Excel/Spreadsheet_Excel_Reader.php");

    $exldata = new \Spreadsheet_Excel_Reader();


}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!