Skip to content
Advertisement

__set() and __get() not work with isset() and empty(). How solve?

having:

class foo {
    
    private $myproperty;
    
    public
    function __construct() {
        if (
            ( !isset( $_SESSION ) ) &&
            ( session_status() == PHP_SESSION_NONE )
        ) {
            session_start();
        }
    
    public
    function __set( $name, $value ) {
        if ( property_exists( "foo", $name ) ) {
            $_SESSION[ $name ] = $value;
        }
    }
    
    public
    function __get( $name ) {
        if ( property_exists( "foo", $name ) ) {
            return $_SESSION[ $name ];
        }
    }
    
}

Doing:

$foo = new $foo();
$foo->myproperty = "value";
if ( isset ($foo->myproperty ) ) {
  echo "myproperty setted";
} else {
  echo "myproperty not setted"
}

Why return "myproperty not setted"? Same problem if i replace isset with empty. Is a bug? If no, how i can fix it?

Advertisement

Answer

You should use the __isset() method. Here is an example:

<?php
class Foo {
    private $myproperty;

    public function __construct() {
        if (
            ( !isset( $_SESSION ) ) &&
            ( session_status() == PHP_SESSION_NONE )
        ) {
            session_start();
        }
    }

    public function __set( $name, $value ) {
        if ( property_exists( "foo", $name ) ) {
            $_SESSION[ $name ] = $value;
        }
    }

    public function __get( $name ) {
        if ( property_exists( "foo", $name ) ) {
            return $_SESSION[ $name ];
        }
    }
    
    public function __isset($propertyName){
        return isset($_SESSION[$propertyName]);
    }
}
        


$foo = new foo();
$foo->myproperty = "value";

if ( isset($foo->myproperty) ) {
  echo "myproperty setted";
} else {
  echo "myproperty not setted";
}
?>

Note that this way empty() will work too because internally it uses __isset().

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement