0

可能重复:
通过字符串
PHP 方法链接获取 PHP 类属性?

我有一个类,其中方法返回调用它的实例。如何直接从函数的返回值访问属性(其名称存储在变量中)?这是我现在正在尝试的:

class MyClass {
    public $variable_one;

    public function function_one() {
        $variable = 'last';
        // The problematic line: call method, access property on result
        return $this->function_two->$variable;
    }

    public function function_two($params = array()) {
        if (is_array($params)) {
            $params = http_build_query($params, NULL, '&');
        }

        $this->option(CURLOPT_COOKIE, $params);
        return $this;
    }
}
4

1 回答 1

0

$this变量是特殊的,仅存在于类中。如果您在名为变量的类中有一个属性,那么您可以$this->variable从该类中访问它。

class MyClass
{
   private $variable;
   public function getVariable()
   {
       return $this->variable;
   }
}
于 2012-07-12T03:03:26.817 回答