在默认的Index/controller下面创建一个Demo2.php文件
写个类
class Demo2{}
在app/common下创建个Test.php,也写个类
class Test{
public function hello($name){
return 'hello'.$name;
}
}
那么,在demo2中,class Demo2{
public function index($name='thinkphp'){
//想调用Test类中的方法
$test=new \app\common\Test();
return $test->hello($name);
}
}
上面是最经典的调用其他类的方法,也叫传统调用
现在,如果不想这样调用,直接在方法中写Test::hello()方法,怎么办?
可以给Test绑定一个代理
在application 下创建个facade目录,下面创个类文件,Test类
namespace app\facade;
class Test extends \think\Facade{
protected static function getFacadeClass(){
return 'app\common\Test';
}
}
接下来在Demo2中,命名空间下导入静态类(use app\facade\Test),index方法中就可以写
return Test::hello('名称');了
系统中也给好多类,如app类等,到时应该可以这样调用了
如果不想
class Test extends \think\Facade{
protected static function getFacadeClass(){
return 'app\common\Test';
}
}这样写,想直接这样,class Test extends \think\Facade{
}
那就在Demo2中的index方法中写上
\think\Facade::bind('app\facade\Test','app\common\Test'); //静态代理的动态绑定
return Test::hello('名称');
网友评论