Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Readonly Properties?

In using PHP's DOM classes (DOMNode, DOMEElement, etc) I have noticed that they possess truly readonly properties. For example, I can read the $nodeName property of a DOMNode, but I cannot write to it (if I do PHP throws a fatal error).

How can I create readonly properties of my own in PHP?

like image 623
mazniak Avatar asked Dec 31 '08 03:12

mazniak


People also ask

What are the properties of read only?

Read only means that we can access the value of a property but we can't assign a value to it. When a property does not have a set accessor then it is a read only property. For example in the person class we have a Gender property that has only a get accessor and doesn't have a set accessor.

How do I change the readonly property?

You can use mapping modifiers to change a readonly property to mutable in TypeScript, e.g. -readonly [Key in keyof Type]: Type[Key] . You can remove the readonly modifier by prefixing the readonly keyword with a minus - .

How do you access the properties of an object in PHP?

Within class methods non-static properties may be accessed by using -> (Object Operator): $this->property (where property is the name of the property). Static properties are accessed by using the :: (Double Colon): self::$property .


1 Answers

You can do it like this:

class Example {     private $__readOnly = 'hello world';     function __get($name) {         if($name === 'readOnly')             return $this->__readOnly;         user_error("Invalid property: " . __CLASS__ . "->$name");     }     function __set($name, $value) {         user_error("Can't set property: " . __CLASS__ . "->$name");     } } 

Only use this when you really need it - it is slower than normal property access. For PHP, it's best to adopt a policy of only using setter methods to change a property from the outside.

like image 92
too much php Avatar answered Sep 19 '22 12:09

too much php