Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Magic Methods php, __call __get and __set?

my question is, say we have a class:

class SomeClass{

    private $someProperty;


    public function __call($name,$arguments){
        echo "Hello World";
}

Now when I say:

$object = new SomeClass();
$object->someMethod();

the __call method in my class will be called.

When I say

$object->getSomeProperty();

will __call again be called? If so, what is __get and __set magic methods are for?

When I say

$object->someProperty;

then will __get($someProperty) be called? or will it be __set($someProperty) ?

like image 665
Koray Tugay Avatar asked Dec 04 '22 12:12

Koray Tugay


2 Answers

Anytime an inaccessible method is invoked __call will be called.

Anytime you try to read a property __get will be called, whether it's echo $obj->prop; or $var = $obj->prop;

And lastly, anytime you try to write to a property the __set magic method will be called.

like image 186
Marcus Recck Avatar answered Dec 09 '22 15:12

Marcus Recck


will __call again be called?

Yes.

If so, what is __get and __set magic methods are for?

see below:

When I say

$object->someProperty;

then will __get($someProperty) be called? or will it be __set($someProperty) ?

__get('someProperty') because this expression is not an assignment.

like image 23
Fabian Schmengler Avatar answered Dec 09 '22 16:12

Fabian Schmengler