我有这堂课:
class Search
{
protected static $Basics;
public function __construct() {
self::$Basics = new Basics();
}
public static function getT() {
return self::$Basics->get('keywords/t');
}
public static function isAvailable($keyword) {
return self::$Basics->get('keywords/available', ['keyword' => $keyword])['available'];
}
}
班级Basics
非常简单:
class Basics
{
public function __construct()
{
//some code..
}
public function get($keyword, $param = null)
{
return ['available' => true];
}
}
致电getT
函数:
use App\Libraries\Search;
class GV
{
public function test() {
echo Search::getT() ? 'ok' : 'bad';
}
}
但是,当我在课程getT
中运行Search
函数时,会返回此错误:Call to a member function get() on a non-object
我该怎么办?
答案 0 :(得分:1)
您正在Search
静态(Search::getT();
)内部调用方法,该方法永远不会触发__construct()
方法。
__construct()
在实例化类($search = new Search;
)时被触发,而不是在调用静态方法(Class::method();
)时被触发。
只需实例化您的搜索对象:$search = new Search;
像这样:
use App\Libraries\Search;
class GV
{
public function test() {
$search = new Search;
echo $search::getT() ? 'ok' : 'bad';
}
}