如果我有这样的代码:
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".
Run Code Online (Sandbox Code Playgroud)
是否可以从方法中打印存储为变量名称的人名?
由于这不是标准程序,我猜这是个坏主意.
我查了一下,我找不到任何关于它的东西.
Ric*_*dle 20
对象可以有多个名称,也可以没有名称.这会发生什么:
$John = new Person();
$Richie = $John; // $John and $Richie now both refer to the same object.
print $Richie->about();
Run Code Online (Sandbox Code Playgroud)
或者在这里:
function f($person)
{
print $person->about();
}
f(new Person());
Run Code Online (Sandbox Code Playgroud)
如果对象需要知道自己的名称,那么他们需要将其名称显式存储为成员变量(如$age和$height).