class User {
public $name;
public function __construct($name) {
$this->name = $name;
}
public function sayHi() {
echo "Hi, I am $this->name!";
}
}
Can someone explain to me word by word, what is meant by $this->name=$name? I keep thinking like, $this goes into(hence the -> sign) name which is (hence the = sign) $name defined beforehand. Also I dont see the need of that function?
Could just go like this :
class User {
public $name;
public function sayHi() {
echo "Hi, I am $name!";
}
}
I'm out of idea thinking about this .. thanks in advance.
When you are creating a new instance of the class User
with the __construct
parameter $name
, by $this->name
it is set to the $name
property of the class. In your second example $name
does not get any value because you are nowhere assigning any value to it.
You could also have it like this for better understanding:
class User {
public $nameProperty;
public function __construct($name) {
$this->nameProperty = $name;
}
public function sayHi() {
echo "Hi, I am $this->nameProperty!";
}
}
$this
refers to the class you are currently in. So when you create a new class of User
, you can pass a name by using the $name
parameter. This parameter then gets assigned to the $nameProperty
and in your method sayHi()
you would then echo the assigned name.
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
}
}
In the context of a class method, when you want to access the class properties, you have to use $this->property. Without $this, you are actually accessing a variable in the scope of the method, which in your case, is the parameter $name.
The function __construct() is the constructor for your class object. So if you would instantiate an object, you would execute the code inside the constructor. Example:
$user = new User("John"); // you are actually calling the __construct method here
echo $user->name; // John
Hope that enlightens you.