Douglas Zanotta
Douglas Zanotta

Reputation: 62

PHP Magic Methods with unexpected behaviour

<?php

class MyClass{

    private $props;

    public function __constructor(){
        $this->props = array();
    }

    public function __get($field) {
        return $this->props[$field];
    }

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


$myInstance = new MyClass();
$myInstance->a = "Some string";

echo "Property 'a' has value ",$myInstance->a,"<br />"; // First echo
echo "Is property 'a' empty? ",(empty($myInstance->a) ? "Yes, but it shouldn't!" : "No, as expected"); // Second echo
// Output:
// Property 'a' has value Some string
// Is property 'a' empty? Yes, but it shouldn't!


$temp = $myInstance->a;
echo 'Variable $temp has value ',$temp,"<br />";
echo 'Is variable $temp empty? ',(empty($temp) ? "Yes, but it shouldn't!" : "No, as expected");
// Output:
// Variable $temp has value Some string
// Is variable $temp empty? No, as expected

?>

I've made this small class and code to ilustrate exactly what is my problem.

As you can see, my class has one property called $props. This property will be a array with all other properties. My array $props will be populated with Magic Method __set, when a instance of this class has an atribution at a nonexistent property (http://php.net/manual/en/language.oop5.magic.php).

This part works properly.

When I want to read a nonexistent property, PHP should call MyClass's __get method and return the value stored in $props property. It works fine in first echo (value is correctly returned). But, if I use this reading action when I'm sending its return to one empty() function, it always returns TRUE, as you can see in second echo's return (in other words, php seems can't read $props property properly)

If I store property's value in a $temp variable and use this variable, my problem is solved, BUT I don't want to just solve this problem. I want to understand what is happening here.

Is it a PHP bug on Magic Methods? Is it a empty funcion bug? Is my code doing something meaningless? (Most probable answer)

Before you ask: I'm running my php server on a Windows machine and my php version is 5.3.8

Thanks in advance.

Upvotes: 0

Views: 49

Answers (1)

Alessandro
Alessandro

Reputation: 1453

Because empty check if a variable exists and then if it is empty. If it doesn't exists (in your case because you're not passing it a variable), then it returns true

Checkout the doc page: http://php.net/manual/en/function.empty.php

Upvotes: 1

Related Questions