4

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) ?

2 Answers 2

16

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.

4
  • so when I say $obj->prop __get is called but if it is $obj->prop = $something __set is called? And this is only true if prop is not public? Commented Jan 28, 2013 at 18:26
  • And you mean anytime a method that does not exists or is it really anytime a method is called __call is called? Commented Jan 28, 2013 at 18:26
  • __set is only called when you have an instance of an object. Setting variables inside of your class will not call __set. Regardless, private properties can't be accessed when you have an instance of an object, so yes, only public properties, when changed, will invoke __set. As for __call, it is only invoked when a method is inaccessible, so yes, when the method doesn't exist it will be invoked. Commented Jan 28, 2013 at 18:31
  • Can you please take a look at: stackoverflow.com/questions/14571565/… Commented Jan 28, 2013 at 21:42
1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.