John Davidson

PHP - is there any way to differentiate between unset and null?

0 comments
Message:


Consider the following code:


class Test {
public $definedButNotSet;
}

$Test = new Test();

var_dump($Test->definedButNotSet=== null); // true
var_dump(isset($Test->definedButNotSet)); // false

$Test->definedButNotSet = null;
var_dump(isset($Test->definedButNotSet)); // false

It seems to me, that PHP implicitly sets a defined variable to null. Is there any way to circumvent this, and differentiate between a variable that was explicitly set to null and a variable that was only defined, but not set to any value?


UPDATE:


What I basically want to see if during the runtime the definedButNotSet variable was updated or not. So my expected results for the following code are:


$Test = new Test();
var_dump(isset($Test->definedButNotSet)); // false

$Test->definedButNotSet = null;
var_dump(isset($Test->definedButNotSet)); // true expected here but php returns false

An actual use case where the difference indeed matters, and basically this would be my use case also: when updating rows in a database, I would like to update the rows of a table, that the user changed only when an update method is called. For this, I have to know, if the user implicitly modified any variable in the class representing the row in the table or not.


I am running a custom ORM, which at the moment, fails, if I insert a row in a database with a column which has a default_timestamp method set as the default value, and in the same runtime, I try to update the same row again, as the database set value is not reflected in my class instance, thus at the update PHP sends to him that his value is null, which is not allowed.



My Answer:
In PHP, there is no direct way to differentiate between a variable that was explicitly set to null and a variable that was only defined but not set to any value. When you access a property of an object that has been defined but not set, PHP will return null by default.

One way to work around this limitation is to create a separate flag variable to track whether the property has been explicitly set to null or not. Here's an example:

php
class Test {
public $definedButNotSet;
public $isNull = false;
}

$Test = new Test();

var_dump($Test->definedButNotSet === null && !$Test->isNull); // true
var_dump(isset($Test->definedButNotSet)); // false

$Test->definedButNotSet = null;
$Test->isNull = true;
var_dump(isset($Test->definedButNotSet)); // true


By using the additional `$isNull` flag variable, you can differentiate between a property that was explicitly set to null and a property that was only defined but not set.

Rate this post

4 of 5 based on 4473 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us