PHP对象实例可以知道其名称吗? [英] Can a PHP object instance know its name?
本文介绍了PHP对象实例可以知道其名称吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有这样的代码:
class Person {
$age;
$height;
$more_stuff_about_the_person;
function about() {
return /* Can I get the person's name? */;
}
}
$John = new Person();
$Peter = new Person();
print $John->about(); // Print "John".
print $Peter->about(); // Print "Peter".
是否可以从方法中打印存储为变量名的人员姓名?
Is it possible to print the person's name, stored as the variable name, from the method?
由于它不是标准程序,所以我认为这是个坏主意.
As it's not standard procedure, I'm guessing it's a bad idea.
我查了一下,找不到任何东西.
I've looked it up and I can't find anything about it.
推荐答案
否.对象可以有多个名称,也可以没有名称.这里会发生什么:
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();
或此处:
function f($person)
{
print $person->about();
}
f(new Person());
如果对象需要知道自己的名称,则需要将其名称显式存储为成员变量(如$age
和$height
).
If the objects need to know their own names, then they need to explicitly store their names as member variables (like $age
and $height
).
这篇关于PHP对象实例可以知道其名称吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文