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有什么好处。
除非您使用 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.
$this->variable
是指类的值variable
。由于您在类中,因此$this
引用Foo
并且您正在调用该类的Amount
变量。
在另一个函数中调用类时,它会派上用场。与其提取值并将其分配给另一个变量,不如使用$this->Amount