特征构造函数中的未定义变量

Undefined variable in trait constructor

我不熟悉使用特征的想法。我的理解是,行为可以在 classes 中水平共享。在我的项目中,下面的代码在每个class.

的顶部重复使用
class Loader {

    protected $options;

    /**
    * Loader constructor.
    */
    public function __construct() {
        $this->options = get_option( 'xenword_options' );
        $this->init();
    }

由于这是在数十个 classes 中完成的,构建特质是否是一个很好的追求方向?

这是我失败的尝试。创建了一个名为 Options.php 的文件。内容如下:

trait getOptions {
    public $options;

    public function __construct() {
        $this->$options = get_option('xenword_options');
    }
}

不幸的是,PhpStorm 给出了一条消息 Undefined variable 'options.' 当此代码位于 class 结构中时,这不是问题。

由于我是 traits 的新手,任何建议和指示都将不胜感激。先感谢您。

$this->$options 是语法错误。

你需要 $this->options。

你快到了。

@SignpostMarv 在 $this->$option 错误的部分是正确的,不是因为它是语法错误,而是因为 $ 有错字,应该是 [=13] =] 不是 ->$options(你可以检查 http://sandbox.onlinephpfunctions.com/code/3a40de64bb87d8838b5368dd6fe69d128603c37b)。

既然你拥有了特质,你必须将它包含在 类

class Loader {
    use starter;
}

trait starter {
    protected $options;

    public function __construct() {
        $this->options = 'xenword_options';
        $this->init();
    }

    public function init() {
      $myClass = __CLASS__;
      echo "{$myClass} started";
    }
}

要对其进行测试,只需执行 new Loader() 即可查看消息。 (检查:http://sandbox.onlinephpfunctions.com/code/55b517142fb8d74b8b5a3e2246c79b6428330297