【问题标题】:Get variable from $this->variable [duplicate]从 $this->variable 获取变量 [重复]
【发布时间】:2012-07-11 18:26:09
【问题描述】:

可能重复:
Get PHP class property by string
PHP method chaining?

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

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;
    }
}

【问题讨论】:

  • $this->some_function->$variable 是什么意思?
  • 嗨@bfavaretto 我无法编辑我的问题。请看这个pastebin.com/E0Rh8TpX
  • 我认为您正在寻找方法链接。请参阅上面的链接。
  • 您的脚本包含一些错误,$variable 没有在类中仅通过方法设置,您需要定义变量。但是如果你想调用 function_two 然后返回局部变量。那么你不能使用链接。只有当您的变量在类范围内定义时,您才能使用链接。 function_two 也缺少括号。

标签: php


【解决方案1】:

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

class MyClass
{
   private $variable;
   public function getVariable()
   {
       return $this->variable;
   }
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-08
  • 1970-01-01
  • 2012-10-17
  • 1970-01-01
相关资源
最近更新 更多