Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do PHP magical methods have to be public?

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 ?

like image 563
TeChn4K Avatar asked Nov 22 '11 17:11

TeChn4K


1 Answers

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.

like image 73
Charles Sprayberry Avatar answered Sep 22 '22 15:09

Charles Sprayberry