为什么在下面的代码和&中使用$ this如果我没有使用然后发生了什么和使用$这有什么好处?

时间:2013-12-02 05:29:37

标签: php this

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的好处是什么。

2 个答案:

答案 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.