7

I use magical methods in my PHP classes but when i try to put them private, I'm warned :

WARN: The magic method __get() must have public visibility and cannot be static in ...

I wouldn't like to have these methods in Eclipse auto completion. (maybe a way with phpdoc ?) So my question is, why must these methods be public ?

5
  • 2
    Only overloading magic methods must be public. This requirement is not enforced on stuff like constructors and destructors.
    – BoltClock
    Commented Nov 22, 2011 at 17:37
  • 4
    These methods will be called from outside the class context, so what's surprising about their need to be public?
    – Kerrek SB
    Commented Nov 22, 2011 at 17:37
  • 1
    @KerrekSB : call inaccessible attribute from outside class context mean call __get method from outside ? so it would be the answer !
    – TeChn4K
    Commented Nov 22, 2011 at 17:48
  • What php version is this? I don't get any such warning. Commented Nov 22, 2011 at 17:53
  • @ExplosionPills enable error reporting
    – Daniel W.
    Commented Mar 28, 2014 at 8:38

1 Answer 1

9

Because you are invoking the methods from a scope outside of the class.

For example:

// this can be any class with __get() and __set methods
$YourClass = new YourOverloadableClass();

// this is an overloaded property
$YourClass->overloaded = 'test';

The above code is "converted" to:

$YourClass->__set('overloaded', 'test');

Later when you get the property value like:

$var = $YourClass->overloaded;

This code is "converted" to:

$YourClass->__get('overloaded');

In each case the magic method, __get and __set, are being invoked from outside the class so those methods will need to be public.

3
  • I don't think "public scope" is a word... at least it obscures what's really going on :-(
    – Kerrek SB
    Commented Nov 22, 2011 at 17:52
  • @Kerrek SB: I think a more appropriate term would be "calling scope".
    – BoltClock
    Commented Nov 22, 2011 at 18:31
  • You're right, public scope isn't really descriptive of what's going on. Will modify the answer to be clearer on what is happening. Commented Nov 22, 2011 at 19:22

Not the answer you're looking for? Browse other questions tagged or ask your own question.