Can a PHP object instance know its name?

前端 未结 4 714
一向
一向 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.

    0 讨论(0)
  • 2021-01-17 17:54

    No. Objects can have multiple names, or no names. What would happen here:

    $John = new Person();
    $Richie = $John;      // $John and $Richie now both refer to the same object.
    print $Richie->about();
    

    or here:

    function f($person)
    {
        print $person->about();
    }
    
    f(new Person());
    

    If the objects need to know their own names, then they need to explicitly store their names as member variables (like $age and $height).

    0 讨论(0)
  • 2021-01-17 17:54

    This example might be helpful currently there is no method that tells you the object name you have to specify yourself like in the code below:

    class Person {
    
        public $age=0;
        public $height=0;
        public $objPerson='';
    
        function about($objPerson,$age,$height) {
            return 
                    'Person Object Name: '.$objPerson.'<br>'.
                    'Age: '.$age.'<br>'.
                    'height: '.$height.'ft<br><hr>';
        }
      }
    
    $John = new Person();
    
    $Peter = new Person();
    
    print $John->about('John',25,'5.5'); 
    
    print $Peter->about('Peter',34,'6.0'); 
    
    0 讨论(0)
  • 2021-01-17 17:55

    Eje211, you're trying to use variables in very bizarre ways. Variables are simply data holders. Your application should never care about the name of the variables, but rather the values contained within them.

    The standard way to accomplish this - as has been mentioned already, is to give the Person class a 'name' property.

    Just to re-iterate, do not rely on variable names to determine the output/functionality of your application.

    0 讨论(0)
提交回复
热议问题