/ Published in: PHP
I like using public properties, as they greatly aid in API development and proper encapsulation. Here's my solution for having the ease of public variable getting without the dangers of public variable setting.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
<?php class Example { // 1. Change your desired read-only property from public to protected. protected $name; // 2. Create this method and add your desired read-only public property. public function __get($property) { if ($property == 'name') { return $this->name; } } public function __construct($name) { $this->name = $name; } } // Demo: $e = new Example("test"); echo $e->name . "\n"; // <-- Output: test $e->name = 'asdf'; // <-- PHP Fatal error: Cannot access protected property Example::$name