Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
NULL and unset has unpredictable behavior
<?php
// Conclusion: NULL and unset have unpredictable behavior
// === NULL are in some cases same as unset ===
// This code will assign a value, then assign NULL, and the result will show that
// PHP think this is same as unset()
$a = "test";
$a = NULL// will be same as unset()
echo (isset($a) ? "true" : "false") . "\n";
// Will output:
// false
// === NULL are in some cases NOT same as unset ===
// This code will strangely not work, because it is not in this case
// sufficient to set previous and next to NULL without using the unset() first().
date_default_timezone_set('America/Los_Angeles');
class Test {
public $previous, $next = NULL;
public $name = NULL;
public function __construct($name) {
$this->name = $name;
}
public function __clone() {
// Try to uncomment next line, and application will work
//unset($this->previous); unset($this->next);
$this->previous = NULL; $this->next = NULL;
}
public function __toString() {
return $this->name . ' [' . ($this->previous !== NULL ? '<' : '-') . ' ' . ($this->next !== NULL ? '>' : '-') . ']';
}
}
// Create some test objects
$a = new Test('a'); $b = new Test('b');
// Link them together
$a->next =& $b; $b->previous =& $a;
// Clone and print
echo "before cloning:\n" . $a . "\n" . $b . "\n";
$b = clone $a;
echo "These two should NOT look the same:\n" . $a . "\n" . $b . "\n";
// Will output two similar rows on last line, but they should be different:
// before cloning:
// a [- >]
// b [< -]
// These two should NOT look the same:
// a [- >]
// a [- >]
// If we however uncomment the line starting with 'unset' the output will however be correct:
// before cloning:
// a [- >]
// b [< -]
// These two should NOT look the same:
// a [- >]
// a [- -]
// Also note that if you would only do the unset and not the
// NULL assignment, you would receive the following warnings from PHP:
// PHP Notice: Undefined property: Test::$previous in /home/vsdev/Desktop/phptest.php on line 17
// PHP Notice: Undefined property: Test::$next in /home/vsdev/Desktop/phptest.php on line 17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.