Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I need to know about magic function __isset() and normal function isset(). Actually what is the real difference between php language construct isset() and php magic method __isset() ? When I google it they told that __isset() is a magic function. What are difference between common php functions and magic functions in php?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
306 views
Welcome To Ask or Share your Answers For Others

1 Answer

isset()

It is a language construct that checks the initialization of variables or class properties:

$a = 10;

isset($a);     // true
isset($a, $b); // false

class Test
{
    public $prop = 10;
}

$obj = new Test;
isset($obj->prop); // true

__isset()

It is a magic method that is invoked when isset() or empty() check non-existent or inaccessible class property:

class Test
{
    public function __isset($name) {
        echo "Non-existent property '$name'";
    }
}

$obj = new Test;
isset($obj->prop); // prints "Non-existent property 'prop'" and return false

Difference:

           isset()                               __isset()
Language construct                    | Magic method
                                      |
Always return bool                    | Result depends on custom logic
* | Must be invoked in code | Called automatically by event | Unlimited number of parameters | Has only one parameter | Can be used in any scope | Must be defined as method** | Is a reserved keyword | Not a reserved keyword | Can't be redefined (Parse error) | Can be redefined in extended class***

__isset() result anyway will be automatically casted as bool.

Actually you can define custom function __isset() but it has nothing to do with the magic method.

See this example.


Magic Methods

Unlike common functions can be defined only in class scope and invoked automatically on specific events such as: inaccessible method invocation, class serialization, when unset() used on inaccessible properties and so on. See also this official documentation: Overloading.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...