Return to Snippet

Revision: 55239
at January 31, 2012 09:14 by phpexpert

Initial Code

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

Initial URL

Initial Description
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.

Initial Title
PHP Read-Only Public Properties

Initial Tags

Initial Language