Home > Blockchain >  How can I make my class variable assignment dynamic?
How can I make my class variable assignment dynamic?

Time:05-05

In the following code, I want to assign an $settings's key, help to a constant class variable value, $To_default. However, I am told Constant expression contains invalid operations. Is there any way I can get around this?

class EmailClass extends PluginBase {

  private $To_default = '[email protected]';

  protected $settings = array(
    'To'=>array(
      'type'=>'text',
      'label'=>'To',
      'help'=>$this->To_default, // Constant expression contains invalid operations
    ),
  );

I've tried declaring $To_default in various ways including private const $To_default, static private $To_default, etc. but none worked. $settings is not static, as you can see, so I don't understand why this is a problem.

CodePudding user response:

You can not specify a default value that refers to another class property ($settings is an array that tries to read $To_default).

My recommendation is that $settings can be the result of a getter method, for example getSettings, and inside of it you can build an array and return it.

By doing do this, you can also decide to override the $To_default value with a setTo method.

Here is an example:

<?php

class EmailClass extends PluginBase {
    private string $toDefault = '';

    /**
     * @param string $toDefault
     */
    public function __construct( string $toDefault = '[email protected]' ) {
        $this->toDefault = $toDefault;
    }

    /**
     * @param string $toDefault
     */
    public function setToDefault( string $toDefault ): void
    {
        $this->toDefault = $toDefault;
    }

    public function getSettings(): array
    {
        return [
            'TO' => [
                'type' => 'text',
                'label' => 'To',
                'help' => $this->toDefault,
            ]
        ];
    }

}

CodePudding user response:

Don't know deep technical explanation for this but I think this is because normally you initialize properties in the constructor, like so:

class EmailClass 
{
private $To_default = '[email protected]'; // not a constant, so better throw it into constructor too
protected $settings;

public function __construct() {
    $this->settings = array(
    'To'=>array(
    'type'=>'text',
    'label'=>'To',
    'help'=>$this->To_default
    )
    );
}
}

Analogical I don't know why: 'if isset(expression)' doesn't work but it doesn't have to. There's a better solution: 'if(expression)'. This is just how we do it.

  • Related