0

我试图创建一个带有函数的基本类。一旦创建了类的实例,new BaseClass("hello")构造函数就会将参数保存到变量中。应该返回这个->ret_text()变量,但它不起作用。错误是:unexpected T_OBJECT_OPERATOR

class BaseClass {
    var $txt;

    function __construct($text) {
        $txt = $text;
    }

    public function ret_text() {
        return $txt;
    }
}

echo (new BaseClass("hello"))->ret_text();
4

1 回答 1

4

$this->variableName您应该使用where$this引用您所在的类来访问您的类变量。

在您的示例$txt中,不是类变量$txt,而只是当前函数(或其他东西)的__construct()变量ret_text()。此外,您不能在类初始化后直接调用方法,即(new Class())->methodName();不适用于PHP version < 5.4. 但是,它适用于PHP version => 5.4.

而是试试这个:

class BaseClass {
    var $txt;

    function __construct($text) {
        $txt = 'This is a variable only for this method and it\'s not $this->txt.';
        $this->txt = $text;
    }

    public function ret_text() {
        $txt = 'This is a variable only for this method and it\'s not $this->txt.';
        return $this->txt;
    }
}

$bc = new BaseClass("hello");
echo $bc->ret_text();
于 2013-05-31T07:55:26.897 回答