0

Possible Duplicate:
PHP Readonly Properties?

I want a property to be publicly visible:

echo $object->prop;

but I don't want to be modifiable.

Are there other options to make this happen, besides using __get?

Community
  • 1
  • 1
Alex
  • 66,732
  • 177
  • 439
  • 641
  • 3
    Are you looking for read only properties? http://stackoverflow.com/questions/402215/php-readonly-properties – Aaron McIver Feb 10 '12 at 20:04
  • yes, something like that. But the solution you linked uses __get too – Alex Feb 10 '12 at 20:09
  • If you don't want to use `__get`, then yes, getter methods are the best bet. You could alternatively implement `ArrayAccess` but this likely isn't any more performant that `__get` –  Feb 10 '12 at 20:17
  • As an alternative to to __get() and regular getter/setter I sometimes take approach to copy public properties to protected/private when object needs to enter a "locked" state. Not quite the same as making them read-only, but reduces mess while maintaining performance when nothing really cares about the values from outside. :) – Slava Feb 10 '12 at 20:31
  • the question is somewhat misphrased. if you want to modify a property you use a setter. A getter only provides access to the property. The magic methods __get and __set are not Getters and Setters though. They are error handlers that get triggered when trying to access/mutate an inaccessible property. – Gordon Feb 10 '12 at 20:40
  • there is no other way to do read only public properties. many might suggest that you make the property protected and just make a getter method. $object->getProp(). – dqhendricks Feb 10 '12 at 20:48

2 Answers2

0

Other ways I can think of:

  1. Use a __set() function and ignore the setting.
  2. Don't use that variable at all, but create a getVal() function, and no setVal() function.

Hope this helps :)

Mikhail
  • 8,692
  • 8
  • 56
  • 82
  • #1 won't work if the variable is visible to outsiders -- `__set` only runs when someone tries to set a property that doesn't exist, or is private. In cases where `__set` would run, you'd need a `__get` too. – cHao Feb 11 '12 at 00:12
0

Are there other options to make this happen, besides using __get?

No, but there is feature request for it: https://bugs.php.net/bug.php?id=46506 so you can vote for importance of it and hope that this will be resolved in near future.

But I don't think it will be near future since this feature will create a lot of confusion, like objects stored in properties - they are only references to the object, so making them visible allows you to operate on it's methods / properties.

As for now, creating proper getter for every property, that you want to be read-only, seems to be the best solution.

dev-null-dweller
  • 29,274
  • 3
  • 65
  • 85