Why do PHP magical methods have to be public?
Asked Answered
Y

1

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 ?

Yearn answered 22/11, 2011 at 17:32 Comment(5)
Only overloading magic methods must be public. This requirement is not enforced on stuff like constructors and destructors.Rakia
These methods will be called from outside the class context, so what's surprising about their need to be public?Inquietude
@KerrekSB : call inaccessible attribute from outside class context mean call __get method from outside ? so it would be the answer !Yearn
What php version is this? I don't get any such warning.Briony
@ExplosionPills enable error reportingFlem
P
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.

Pleasantry answered 22/11, 2011 at 17:45 Comment(3)
I don't think "public scope" is a word... at least it obscures what's really going on :-(Inquietude
@Kerrek SB: I think a more appropriate term would be "calling scope".Rakia
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.Pleasantry

© 2022 - 2024 — McMap. All rights reserved.