为什么 class 亲子关系函数不应该有全局 $$Obj 语句
Why shouldn't a class parentage function have a global $$Obj statement
在 php.net 手册中的 Class/Objects 示例中,这个被高度否决的 comment was left
In order to avoid an "Undefined variable" error, the class_parentage fucntion should have the global $$obj stattement :
function class_parentage($obj, $class) {
global $$obj;
if (is_subclass_of($GLOBALS[$obj], $class)) {
echo "L'objet $obj appartient à la classe " . get_class($$obj);
echo " une sous-classe de $class\n";
} else {
echo "L'object $obj n'appartient pas à une sous-classe $class\n";
}
}
请有人解释为什么这是个糟糕的建议或者为什么反对者是错误的。
首先,您通常应该避免使用全局变量,除非确实有必要并且在本例中显然不是这样。全局变量会导致很多问题,评论者指出了很多问题 here(这是关于 c++ 的,但概念在所有语言中都是相同的)。
但是,他正确地指出,当 $global
中的密钥在 $_GLOBALS
中不存在时,文档中提供的代码可能会导致 "undefined index" 错误。
但解决方案绝对不是简单地为此检查创建一个空的全局变量。实际上,有一个 php 函数专门用于检查数组是否具有特定键:array_key_exists()
。所以正确的解决方案是:
if(!array_key_exists($global, $_GLOBALS)){
echo "class does not exist"
}
最后,英语论坛对post法语文本不是很友好。互联网的通用交流语言是英语,这种行为在别人看来可能很傲慢。
在 php.net 手册中的 Class/Objects 示例中,这个被高度否决的 comment was left
In order to avoid an "Undefined variable" error, the class_parentage fucntion should have the global $$obj stattement :
function class_parentage($obj, $class) {
global $$obj;
if (is_subclass_of($GLOBALS[$obj], $class)) {
echo "L'objet $obj appartient à la classe " . get_class($$obj);
echo " une sous-classe de $class\n";
} else {
echo "L'object $obj n'appartient pas à une sous-classe $class\n";
}
}
请有人解释为什么这是个糟糕的建议或者为什么反对者是错误的。
首先,您通常应该避免使用全局变量,除非确实有必要并且在本例中显然不是这样。全局变量会导致很多问题,评论者指出了很多问题 here(这是关于 c++ 的,但概念在所有语言中都是相同的)。
但是,他正确地指出,当 $global
中的密钥在 $_GLOBALS
中不存在时,文档中提供的代码可能会导致 "undefined index" 错误。
但解决方案绝对不是简单地为此检查创建一个空的全局变量。实际上,有一个 php 函数专门用于检查数组是否具有特定键:array_key_exists()
。所以正确的解决方案是:
if(!array_key_exists($global, $_GLOBALS)){
echo "class does not exist"
}
最后,英语论坛对post法语文本不是很友好。互联网的通用交流语言是英语,这种行为在别人看来可能很傲慢。