News Feed
Sections




News Archive
Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

Cormac's Blog:
Read-only object variables in php using magic methods
January 23, 2009 @ 12:09:51

This new post on Cormac's blog shows a little trick you can use to make "read-only" object variables with the help of the handy magic methods built in to PHP5.

You can create read-only object variables by using the "private" keyword and the __get() and __set() magic methods. [...] So now classWithReadOnlyVar::readOnlyVar is only settable from inside the class, but you can read it from anywhere.

His example code initially sets up the read-only variable as a property of the example class. The __get magic method is called to correctly fetch the value but the __set intercepts anything trying to change its value. This same sort of thing can be accomplished with the protected/private keywords in PHP5.

1 comment voice your opinion now!
readonly object variable magic method example


blog comments powered by Disqus

Similar Posts

Webification.com: Roundup of 17 Best PHP Template Engines

In Coding: Laravel 4 Authentication A Comprehensive Tutorial

Chris Roane's Blog: The Last Few Years: What a PHP Programmer Has Learned

Matthew Weier O'Phinney's Blog: Syntax Highlighting for Technical Presentations

DevShed: Positioning Strings with the show_xy() Method in PDF Documents with PHP 5


Community Events

Don't see your event here?
Let us know!


php7 community extension list security interview framework library api laravel5 introduction language example voicesoftheelephpant podcast release laravel series opinion version

All content copyright, 2015 PHPDeveloper.org :: info@phpdeveloper.org - Powered by the Solar PHP Framework