sha*_*mar 16
一旦进入对象的函数,就可以完全访问它的变量,但是要设置它们,你需要比仅使用你想要使用的变量名更具体.要正确指定要使用局部变量,需要使用特殊$this变量,PHP始终将其设置为指向您当前使用的对象.
例如:
function bark()
{
print "{$this->Name} says Woof!\n";
}
Run Code Online (Sandbox Code Playgroud)
每当你在一个对象的函数内部时,PHP自动设置$this包含该对象的变量.您无需执行任何操作即可访问它.
$this是一个伪变量,在从对象上下文中调用方法时可用.它是对调用对象的引用(通常是方法所属的对象,但如果从辅助对象的上下文静态调用该方法,则可能是另一个对象)
一个例子:
<?php
class A
{
function foo()
{
if (isset($this)) {
echo '$this is defined (';
echo get_class($this);
echo ")\n";
} else {
echo "\$this is not defined.\n";
}
}
}
class B
{
function bar()
{
// Note: the next line will issue a warning if E_STRICT is enabled.
A::foo();
}
}
$a = new A();
$a->foo();
// Note: the next line will issue a warning if E_STRICT is enabled.
A::foo();
$b = new B();
$b->bar();
// Note: the next line will issue a warning if E_STRICT is enabled.
B::bar();
?>
Run Code Online (Sandbox Code Playgroud)
输出:
$this is defined (A)
$this is not defined.
$this is defined (B)
$this is not defined.
Run Code Online (Sandbox Code Playgroud)