Can a PHP object instance know its name?

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

提交回复
热议问题