views:

215

answers:

3

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
How will you throw a customized exception?
it will not thrown an exception, but a parse error...
Pascal MARTIN
@user198729 Why would you *want* to throw a customized exception?
meagar
+1  A: 

Use a constant. Keyword const

froadie
+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
Good answer!BTW,what's `__call` used for?
`__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
@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 ?
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
Oh,that's fine.What about this one:http://stackoverflow.com/questions/2331723/how-does-the-local-field-for-relation-work-in-doctrine?I'm really having a hard time converting sql to YAML,especially the `local/foreign` settings in `relation` part..