$this在PHP中是什么意思?
可能重复:$this在PHP中是什么意思?,php,oop,this,keyword,Php,Oop,This,Keyword,可能重复: 你好,, 您能帮助我理解PHP变量名$this的含义吗 感谢您的帮助。$此指您所在的班级 比如说 Class Car { function test() { return "Test function called"; } function another_test() { echo $this->test(); // This will echo "Test function called"; } } 希
你好,, 您能帮助我理解PHP变量名
$this
的含义吗
感谢您的帮助。
$此
指您所在的班级
比如说
Class Car {
function test() {
return "Test function called";
}
function another_test() {
echo $this->test(); // This will echo "Test function called";
}
}
希望这能有所帮助。您可能想看看中的答案
基本上,
$this
指的是当前对象。$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
关键字非常相似,除了它指的是类内的静态方法外,static基本上意味着你不能使用$this
,因为它还不是对象,你必须使用self::setAge()
如果该setAge
方法被声明为静态,则不能从该对象的瞬间调用它
一些供您开始使用的链接:
self
和$this
的用法,而是想知道$this
的意思。这是一种引用自身的方式。。。实际上,self指的是您所在的当前类$这是指您所处类的当前对象实例。它不会回显名为“
的测试函数,因为您正在访问Test
成员变量(该变量不存在),而不是方法Test()
。您需要将其更改为echo$this->test()
…它实际上不是类,而是对象-一个类的实例。实际上它是该类的实例,其中asself
将静态引用该类,而\uuuuu CLASS\uuuuu
将类名称为字符串:-)虽然我理解您是在向OOP新手解释,但请不要将对象称为类$这用于引用对象属性和方法,而self::用于引用类属性和方法。我认为解释两者之间的区别很重要。