Why do PHP magical methods have to be public?

TeChn4K picture TeChn4K · Nov 22, 2011 · Viewed 11.2k times · Source

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 ?

Answer

Charles Sprayberry picture Charles Sprayberry · Nov 22, 2011

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.