What is the PHP equivalent of Javascript's undefined? [closed]

 ̄綄美尐妖づ 提交于 2020-05-15 04:20:12

问题


My assumption followed by question based on the assumption:

Javascript has null and undefined. You can set a variable to be null, implying it has no value, or you can set it to undefined, implying that it isn't known whether it has a value or not - it's just not set at all.

PHP has null, which so far I've used in the same way I'd use null in Javascript. Does PHP have an equivalent of undefined?


回答1:


Not really, undefined has no counterpart in PHP. Comparing JS's undefined to PHP s null doesn't really stack up, but it's as close as you're going to get. In both languages you can assign these values/non-values:

var nothingness = undefined;
$nothing = null;

and, if you declare a variable, but don't assign it anything, it would appear that JS resolves the var to undefined, and PHP resolves (or assigns) that variable null:

var nothingness;
console.log(nothingness === undefined);//true

$foo;
echo is_null($foo) ? 'is null' : '?';//is null

Be careful with isset, though:

$foo = null;
//clearly, foo is set:
if (isset($foo))
{//will never echo
    echo 'foo is set';
}

The only real way to know if the variable exists, AFAIK, is by using get_defined_vars:

$foo;
$bar = null;
$defined = get_defined_vars();
if (array_key_exists($defined, 'foo'))
{
    echo '$foo was defined, and assigned: '.$foo;
}



回答2:


I don't think there is undefined. Rather than checking if something is undefined as you would in JavaScript:

if(object.property === undefined) // Doesn't exist.

You just use isset():

if(!isset($something)) // Doesn't exist.

Also, I think your understanding of undefined is a little odd. You shouldn't be setting properties to undefined, that's illogical. You just want to check if something is undefined, which means you haven't defined it anywhere within scope. isset() follows this concept.

That said, you can use unset() which I guess would be considered the same as setting something to undefined.




回答3:


No. It only has "unset", which is not actually a value at all.




回答4:


undefined is the value you'll get in Javascript when trying to access a property/variable which does not exist. You don't typically set something to undefined.

PHP does not have this mechanism. If you're trying to access a property or variable which does not exist, you will trigger an error of the level E_NOTICE. The script will continue, but the value of the non-existent variable will be substituted by null.

In Javascript you try to access a variable and test whether it you get undefined or not.
In PHP, you use isset($var) to test whether a variable exists before accessing it.



来源:https://stackoverflow.com/questions/17398816/what-is-the-php-equivalent-of-javascripts-undefined

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!