read-only properties in PHP?

前端 未结 4 564
清歌不尽
清歌不尽 2021-01-17 14:18

Is there a way to make a read-only property of an object in PHP? I have an object with a couple arrays in it. I want to access them as I normally would an array

<         


        
4条回答
  •  星月不相逢
    2021-01-17 15:09

    If defined, the magic functions __get() and __set() will be called whenever a non-existing or private property is accessed. This can be used to create "get" and "set" methods for private properties, and for instance make them read-only or manipulate the data when stored or retrieved in it.

    For instance:

    class Foo
    {
      private $bar = 0;
      public $baz = 4; // Public properties will not be affected by __get() or __set()
      public function __get($name)
      {
        if($name == 'bar')
          return $this->bar;
        else
          return null;
      }
      public function __set($name, $value)
      {
        // ignore, since Foo::bar is read-only
      }
    }
    
    $myobj = new Foo();
    echo $foo->bar; // Output is "0"
    $foo->bar = 5;
    echo $foo->bar; // Output is still "0", since the variable is read-only
    

    See also the manual page for overloading in PHP.

提交回复
热议问题