Cheok Yan Cheng
Cheok Yan Cheng

Reputation: 42690

Why isset doesn't return true when I override magic functions __get and __set

I had the following code.

May I know, why isset doesn't return true, when I override magic functions __get and __set

The output I get is

$param->country : US
isset($param->country) : 

<?php

class Param
{
    private $params = array();

    public function __get($name) {
        return $this->params[$name];
    }

    public function __set($name, $value) {
        $this->params[$name] = $value;
    }
}

$param = new Param();
$param->country = "US";
echo "\$param->country : " . $param->country . "\n";
echo "isset(\$param->country) : " . isset($param->country) . "\n";

Upvotes: 0

Views: 295

Answers (3)

Sergiu Paraschiv
Sergiu Paraschiv

Reputation: 10153

It's by design. isset is not a function, it's a language construct and it does not automagically call __get. That's why there's an __isset magic method also.

You'll need PHP >= 5.1.0 though.

Upvotes: 1

Matteo Tassinari
Matteo Tassinari

Reputation: 18584

That is because isset is a language construct which does not call the magic methods, you should also implement the magic method __isset.

See also the docs: http://php.net/manual/en/language.oop5.overloading.php#object.isset

Upvotes: 0

deceze
deceze

Reputation: 522076

__set and __get do not handle isset. You will have to implement the magic method __isset as well.

Upvotes: 5

Related Questions