Posted By

phpexpert on 01/31/12


Tagged

php properties


Versions (?)

PHP Read-Only Public Properties


 / 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.

  1. <?php
  2.  
  3. class Example
  4. {
  5. // 1. Change your desired read-only property from public to protected.
  6. protected $name;
  7.  
  8. // 2. Create this method and add your desired read-only public property.
  9. public function __get($property)
  10. {
  11. if ($property == 'name') { return $this->name; }
  12. }
  13.  
  14. public function __construct($name) { $this->name = $name; }
  15. }
  16.  
  17. // Demo:
  18. $e = new Example("test");
  19. echo $e->name . "\n"; // <-- Output: test
  20. $e->name = 'asdf'; // <-- PHP Fatal error: Cannot access protected property Example::$name

Report this snippet  

You need to login to post a comment.