PHP: immutable public member fields

2019-01-15 13:13发布

I need to create an immutable class which is simply a member field container. I want its fields to be instantiated once in its constructor (the values should be given as parameters to the constructor). I want the fields to be public but immutable. I could have done it with Java using the final keyword before each field. How is it done in PHP?

3条回答
We Are One
2楼-- · 2019-01-15 13:41

You could use the __set() magic method and throw an exception when someone tries to set a property directly.

class ClassName {
    public function __set($key, $value) {
        throw new Exception('Can't modify property directly.');
    }
}

However, this would prevent modification of properties regardless of whether they're public or not.

查看更多
Ridiculous、
3楼-- · 2019-01-15 13:56

magic methods

so you can do better - if you have a dinamyc count of fields

   class ClassName {
        private $fields = array(); 
        // use class : $cl = new ClassName(array('f'=>2,'field_4'=>5,''12));
        // echo $cl->field_4; echo $cl->f;
        public function __construct($data= array()) 
        {
           if (!is_array($data) || !count($data)) throw new Exception('Not enough args')
           foreach ($data as $key=>$val)
           {
              if (is_numeric($key))
                $this->fields['field_'.$key] = $val;
              else
                $this->fields[$key] = $val;
           }     
        }
          /* in this case you can use this class like $cl = new ClassName(12,14,13,15,12); echo $cl->field_1;
      public function __construct() 
    {
           $ata = funcs_get_args();

           if (!count($data)) throw new Exception('Not enough args')
           foreach ($data as $key=>$val)
           {
              if (is_numeric($key))
                $this->fields['field_'.$key] = $val;
              else
                $this->fields[$key] = $val;
           }     
    }
    */
        public function __get($var) {
            if (isset($this->fields[$var]))
                return $this->fields[$var];
            return false; 
            //or throw new Exception ('Undeclared property');
        }
    }
查看更多
男人必须洒脱
4楼-- · 2019-01-15 13:58

You should use __set and __get magic methods and declare that property as protected or private:

/**
 * @property-read string $value
 */
class Example
{
    private $value;

    public function __construct()
    {
        $this->value = "test";
    }

    public function __get($key)
    {
        if (property_exists($this, $key)) {
            return $this->{$key};
        } else {
            return null; // or throw an exception
        }
    }

    public function __set($key, $value)
    {
        return; // or throw an exception
    }
}

Example:

$example = new Example();
var_dump($example->value);
$example->value = "invalid";
var_dump($example->value);

Outputs:

string(4) "test"
string(4) "test"

@property-read should help your IDE acknowledge existence of this magic property.

查看更多
登录 后发表回答