When trying to change it,throw an exception.
+8
A:
class test {
const CANT_CHANGE_ME = 1;
}
and you refer it as test::CANT_CHANGE_ME
chelmertz
2010-02-26 18:13:35
How will you throw a customized exception?
2010-02-26 18:15:34
it will not thrown an exception, but a parse error...
Pascal MARTIN
2010-02-26 18:20:56
@user198729 Why would you *want* to throw a customized exception?
meagar
2010-02-26 18:25:18
+2
A:
I suppose a solution, for class properties, would be to :
- not define a property with the name that interests you
- use the magic
__get
method to access that property, using the "fake" name - define the
__set
method so it throws an exception when trying to set that property. - See Overloading, for more informations on magic methods.
For variables, I don't think it's possible to have a read-only variable for which PHP will throw an exception when you're trying to write to it.
For instance, consider this little class :
class MyClass {
protected $_data = array(
'myVar' => 'test'
);
public function __get($name) {
if (isset($this->_data[$name])) {
return $this->_data[$name];
} else {
// non-existant property
// => up to you to decide what to do
}
}
public function __set($name, $value) {
if ($name === 'myVar') {
throw new Exception("not allowed : $name");
} else {
// => up to you to decide what to do
}
}
}
Instanciating the class and trying to read the property :
$a = new MyClass();
echo $a->myVar . '<br />';
Will get you the expected output :
test
While trying to write to the property :
$a->myVar = 10;
Will get you an Exception :
Exception: not allowed : myVar in /.../temp.php on line 19
Pascal MARTIN
2010-02-26 18:16:10
`__call` is called when you're trying to call a method that doesn't exit in the class (like `__get` is called when you're trying to read a property that doesn't exist in the class) -- see http://fr2.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.methods
Pascal MARTIN
2010-02-26 18:27:23
@Pascal MARTIN ,thanks!I also know that you are an experienced user of symfony/doctrine,can you take a look at this post:http://stackoverflow.com/questions/2339800/how-can-i-fetch-the-entire-tree-in-a-single-query-with-doctrine ?
2010-02-26 18:29:59
You're welcome :-) ;;; Symfony ? hu, I have never really used Symfony -- I might be more of a ZF user ;;; Oh, that question is about Doctrine, I seen, and not Symfony ;;; and I've never used trees with Doctrine yet -- sorry...
Pascal MARTIN
2010-02-26 18:32:34