Can a PHP object instance know its name?

前端 未结 4 743
一向
一向 2021-01-17 16:59

If I have code like this:

class Person {
    $age;
    $height;
    $more_stuff_about_the_person;

    function about() {
        return /* Can I get the per         


        
4条回答
  •  深忆病人
    2021-01-17 17:48

    User defined variables names should be treated as totally transparent to the PHP compiler (or any compiler for that matter). The objects you create are just references to memory that point to the real object. Their name has no meaning. Name is a member of person.

    You can, however, get the variables you want with get_defined_vars()

    foreach (get_defined_vars() as $key => $val) {
       if ($val instanceof Person) {
          echo $key;
       }
    }
    

    This should absolutely not be done, however, and the object would still need to know the order in which the variables were stored. No idea how you would calculate that.

提交回复
热议问题