having:
JavaScript
x
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:
JavaScript
$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:
JavaScript
<?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().