在面向对象的php类中,$this->name = $name是什么意思?


In object oriented php class , what is meant by $this->name = $name?

class User {
  public $name;
  public function __construct($name) {
    $this->name = $name;
  }
  public function sayHi() {
    echo "Hi, I am $this->name!";
  }
}

谁能逐字解释一下$this->name=$name是什么意思?我一直在想,$this进入(因此有->符号)名称,这是(因此有=符号)预先定义的$名称。我也看不出这个函数有什么用?

可以这样写:

class User {
  public $name;
  public function sayHi() {
    echo "Hi, I am $name!";
  }
}

我想不出这个问题…

当您使用__construct参数$name创建类User的新实例时,通过$this->name将其设置为类的$name属性。在第二个示例中,$name没有获得任何值,因为您没有为其分配任何值。

为了更好地理解,你也可以这样写:

class User {
  public $nameProperty;
  public function __construct($name) {
    $this->nameProperty = $name;
  }
  public function sayHi() {
    echo "Hi, I am $this->nameProperty!";
  }
}

$this指的是你目前所在的班级。因此,在创建User的新类时,可以通过使用$name参数传递一个名称。这个参数然后被分配给$nameProperty,在你的方法sayHi()中,你会回显分配的名称。

class User {
   public $name; //declare a public property
   public function __construct($name) {
      $this->name = $name; 
     /* at the time of object creation u have to send the value & that value will be store into a public property which will be available through out the class. like $obj = new User('Harry'); Now this will be set in $this->name & it is available inside any method without declaration.
     */
   }
   public function sayHi() {
     echo "Hi, I am $this->name!"; //$this->name is available here
   }
}

在类方法的上下文中,当您想要访问类属性时,必须使用$this->property。如果没有$this,您实际上是在访问方法范围内的一个变量,在您的例子中,该变量是参数$name。函数__construct()是类对象的构造函数。因此,如果要实例化一个对象,就需要在构造函数中执行代码。例子:

$user = new User("John"); // you are actually calling the __construct method here
echo $user->name; // John

希望对你有所启发。