Accessing Properties Inside Classes in OOP in PHP
Inside class methods, a special variable
$this
will be available to us.
It will point to the object of our
class:
<?php
class User {
public function show() {
var_dump($this); // object
}
}
?>
This means that we can access
the object's properties via $this
.
Let's try. Suppose our object
has a property name
. Let's output
this property in our method:
<?php
class User {
public $name;
public function show() {
return $this->name;
}
}
?>
Now let's create an object of our class:
<?php
$user = new User;
?>
Let's assign the property we need:
<?php
$user->name = 'john';
?>
Now let's call the method, thereby outputting the property value:
<?php
echo $user->show(); // will output 'john'
?>
Into the object of the Employee
class
write the properties name
and salary
.
Create a method that will output the employee's name to the screen.
Create a method that will output the employee's salary to the screen.