调用成员函数获取非对象

时间:2016-05-02 14:40:57

标签: php

我有这堂课:

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

我该怎么办?

1 个答案:

答案 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';
    }
}