$这意味着什么PHP?
答
$this
是指你在课堂上。
例如
Class Car {
function test() {
return "Test function called";
}
function another_test() {
echo $this->test(); // This will echo "Test function called";
}
}
希望这有助于。
答
你可能想在In PHP5, what is the difference between using self and $this? When is each appropriate?
看看答案基本上,$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
关键字是非常相似的除了它指的是静态方法类中,静态基本上意味着你不能使用$this
作为它不是一个对象是,你必须使用self::setAge();
,如果该setAge
方法声明为static那么你不能从该对象的瞬间/叫它object
一些链接供你上手:
+0
虽然我知道你正在向OOP新人解释,但请不要将对象称为类。 $ this用于引用对象属性和方法,而self ::用于引用类属性和方法。 我认为重要的是要解释两者之间的差异。 – Craige 2010-11-08 15:24:48
可能重复:http://stackoverflow.com/questions/151969/php-self-vs-this。另外,请不要在提问中太可爱。 ;) – birryree 2010-11-08 15:00:18
祝贺您在12岁时扩大知识!但由于这与问题无关,您可以编辑该问题以将其删除吗? – 2010-11-08 15:02:07
似乎堆栈溢出的人不知道'我12岁,这是什么'是指。 – JAL 2010-11-08 15:06:25