LPH
LPH

Reputation: 165

Undefined variable in trait constructor

I'm new to the idea of using traits. My understanding is that behavior can be shared in classes horizontally. In my project, the following code is repeatedly used at the top of every class.

class Loader {

    protected $options;

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

Since this is done in dozens of classes, would building a trait be a good direction to pursue?

This was my failed attempt. A file named Options.php was created. The contents are the following:

trait getOptions {
    public $options;

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

Unfortunately, PhpStorm gives a message Undefined variable 'options.' This is not an issue when this code is in a class structure.

Since I'm new to traits, any advice and pointers would be appreciated. Thank you in advance.

Upvotes: 1

Views: 637

Answers (2)

mloureiro
mloureiro

Reputation: 949

You're almost there.

@SignpostMarv is right in the part that the $this->$option is wrong there, not because it is a syntax error, but because there is a typo with the $, should be ->options not ->$options (you can check http://sandbox.onlinephpfunctions.com/code/3a40de64bb87d8838b5368dd6fe69d128603c37b).

And now that you have the trait you must include it in the classes

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

To test it just do new Loader() to see the message. (check: http://sandbox.onlinephpfunctions.com/code/55b517142fb8d74b8b5a3e2246c79b6428330297)

Upvotes: 2

SignpostMarv
SignpostMarv

Reputation: 64

$this->$options is a syntax error.

you want $this->options.

Upvotes: 0

Related Questions