Search code examples
phpclassglobal-variablesundefined

Why shouldn't a class parentage function have a global $$Obj statement


In the php.net manual for Class/Objects examples this highly downvoted 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";
        }
    }

Please could someone explain why this is bad advice or why the downvoters are wrong.


Solution

  • First of all, you should generally avoid global variables, unless it is really necessary and it clearly isn't in this case. Global variables can lead to a multitude of issues, many of them pointed out by commenters here (this is about c++, but the concept is the same in all languages).

    However, he is right in pointing out that the code provided in the docs can lead to an "undefined index" error, when the key in $global does not exist in $_GLOBALS.

    But the solution definitely isn't to simply create an empty global variable just for this check. There is, in fact, a php function specifically designed to check if an array has a specific key: array_key_exists(). So the correct solution would be:

    if(!array_key_exists($global, $_GLOBALS)){
       echo "class does not exist"
    }
    

    Lastly, it isn't very friendly to post french text on a english-speaking forum. The general exchange language of the internet is english and such behaviour might seeem arrogant to others.