You can use the __set() "magic method" to limit what can be done.
PHP Code:
<?php class Test { public $foo; private $bar;
public function __set($varName, $value) { if( ! property_exists($this, $varName)) { throw new Exception("Invalid property '$varName'"); } else { throw new Exception("Private property, keep off"); } } }
$test = new Test(); $test->foo = "This is okay"; try { $test->bar = "This should not be allowed."; } catch(Exception $e) { echo "<pre>".print_r($e, 1)."</pre>"; } try { $test->fubar = "This won't work either."; } catch(Exception $e) { echo "<pre>".print_r($e, 1)."</pre>"; }
(You can use the __get() magic method to access non-public variables, too, which in combination with the __set() above could make them effective read-only.)
"Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
~ Terry Pratchett in Nation
I don't think the initial check to determine if the __set() method needs to be called at all should be slow, since that would be part of the underlying C code. If you actually get into the method itself, then you're in more or less "normal" PHP mode -- but since in this specific case we're throwing exceptions, ideally any developer would then adjust his/her client code to not do that. (sort of like a compilation error in C).
"Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
~ Terry Pratchett in Nation
Bookmarks