$this
指的是当前所在的类。
例如:
Class Car {
function test() {
return "Test function called";
}
function another_test() {
echo $this->test(); // This will echo "Test function called";
}
}
希望这能帮到你。
echo“Test functioned called”
。 您需要将其更改为echo $this->test()
... - ircmaxellself
会静态地引用该类,__CLASS__
则会将类名作为字符串引用 :-) - prodigitalson$this
是一个受保护的变量,用于对象内部,$this
允许您在类文件内部访问。
示例
Class Xela
{
var age; //Point 1
public function __construct($age)
{
$this->setAge($age); //setAge is called by $this internally so the private method will be run
}
private function setAge($age)
{
$this->age = $age; //$this->age is the variable set at point 1
}
}
这主要是变量作用域问题,$this
只能在已经初始化并且引用该对象及其父级的对象内部使用,您可以运行私有方法和设置私有变量,而在作用域外部则不行。
self
关键字也很类似,除了它指的是 类 内的静态方法,静态基本上意味着您不能使用 $this
,因为它还不是一个对象,您必须使用 self::setAge();
,如果那个 setAge
方法被声明为静态的,则您不能从该对象/ 对象
的实例中调用它。
以下是一些让您入门的链接:
self
和$this
的用法,而是想知道$this
具体代表什么意思。 - RobertPitt