Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
318 views
in Technique[技术] by (71.8m points)

php - What is the difference between isset() and __isset()?

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...