- var_dump: documentation ( source)
- in_array: documentation ( source)
<?php
class With_Magic_Methods {
private $_prop = array();
protected $compat_fields = array( '_prop' );
public function __get( $name ) {
if ( in_array( $name, $this->compat_fields, true ) ) {
return $this->$name;
}
}
public function __set( $name, $value ) {
if ( in_array( $name, $this->compat_fields, true ) ) {
return $this->$name = $value;
}
}
public function __isset( $name ) {
if ( in_array( $name, $this->compat_fields, true ) ) {
return isset( $this->$name );
}
return false;
}
public function __unset( $name ) {
if ( in_array( $name, $this->compat_fields, true ) ) {
unset( $this->$name );
}
}
}
class No_Magic_Methods {
public $_prop = array();
}
function run_test() {
$with_magic_methods = new With_Magic_Methods();
$no_magic_methods = new No_Magic_Methods();
echo "\n ***** TEST WITH A DYNAMIC PROPERTY ***** \n\n\n";
// __get()
echo "** Test `__get()` **\n";
echo "With magic methods: ";
var_dump( $with_magic_methods->_dynamic_property );
echo "No magic methods: ";
var_dump( $no_magic_methods->_dynamic_property );
// __isset()
echo "\n\n ** Test `__isset()` **\n";
echo "With magic methods: ";
var_dump( isset( $with_magic_methods->_dynamic_property ) );
echo "No magic methods: ";
var_dump( isset( $no_magic_methods->_dynamic_property ) );
// __set()
echo "\n\n ** Test `__set()` **\n";
$new_value = array( 'test' );
$with_magic_methods->_dynamic_property = $new_value;
$no_magic_methods->_dynamic_property = $new_value;
echo "With magic methods: ";
var_dump( $with_magic_methods->_dynamic_property );
echo "No magic methods: ";
var_dump( $no_magic_methods->_dynamic_property );
// Unset.
unset( $with_magic_methods->_dynamic_property );
unset( $no_magic_methods->_dynamic_property );
echo "\n\n ** Test `__isset()` after an `__unset()` **\n";
echo "With magic methods:";
var_dump( isset( $with_magic_methods->_dynamic_property ) );
echo "No magic methods: ";
var_dump( isset( $no_magic_methods->_dynamic_property ) );
echo "\n\n ** Test `__get()` after an __unset() **\n";
echo "With magic methods:";
var_dump( $with_magic_methods->_dynamic_property );
echo "No magic methods: ";
var_dump( $no_magic_methods->_dynamic_property );
echo "\n\n ** Test `__set()` after an __unset() **\n";
$new_value = array( 'test after an unset' );
$with_magic_methods->_dynamic_property = $new_value;
$no_magic_methods->_dynamic_property = $new_value;
echo "With magic methods:";
var_dump( $with_magic_methods->_dynamic_property );
echo "No magic methods: ";
var_dump( $no_magic_methods->_dynamic_property );
}
run_test();