class Foo {
public $Amount = 10;
public function LoopAmount() {
for( $x = 1; $x <= $this->Amount; $x++ ) {
print $x . "\n";
}
}
}
如果我可以写$x<=$Amount
那么为什么要使用$x<=$this->Amount
,为什么我使用$this
,使用$ this的好处是什么。
答案 0 :(得分:1)
$this->variable
指的是类的值variable
。由于您在课堂上,$this
引用了Foo
并且您正在调用该班级的Amount
变量。
在另一个函数中调用类时它会派上用场。您只需使用$this->Amount
答案 1 :(得分:1)
除非您使用SOLID架构(即面向对象编程)编写代码,否则不会立即获益。
$this
指针的要点是引用对象的属性。这个例子应该使用得更清楚:
class Person {
private $eyeColor;
private $name;
public function __construct($name, $eyeColor) { //when we create a person, they need a name and eye color
$this->name = $name;
$this->eyeColor = $eyeColor;
//now the person has the properties we created them with!
}
public function describe() {
//and now we can use the person's properties anywhere in the class
echo "{$this->name} has {$this->eyeColor} eyes.";
}
public function setName($name) { //this is called a "setter" or "mutator" study about those!
$this->name = $name;
}
}
$Sarah = new Person('Sarah Smith', 'brown');
$Sarah->describe();
//Sarah Smith has brown eyes.
//now, if Sarah gets married and changes her name:
$Sarah->setName('Sarah Doe');
$Sarah->describe();
//Sarah Doe has brown eyes.