$this

The pseudo variable $this is used within a class to access the properties of the calling object (i.e. itself).

 

To access properties of an object use $this with the small arrow -> access operator, and then the name of the property without its $ dollar sign:

 

e.g. $this->name

 

Using $this to access the object's properties:

<?php

class Bike {

	public $make ;
	public $model ;
	public $capacity ;
	public $topSpeed ;
	public $cost ;

	public function display() {

		$output = $this->make . ', ';
		$output .= $this->model . ', ';
		$output .= $this->capacity . ', ';
		$output .= $this->topSpeed . ', ';
		$output .= $this->cost . '<br>';

		return $output;
	}
}

echo "<h1>Exploring an object's pseudo varibale \$this</h1>" ;

$myBike = new Bike ;

$myBike->make = "Ducati" ; //$ sign is not required for variable when using ->
$myBike->model = "Panigale" ;
$myBike->capacity = "1200" ;
$myBike->topSpeed = "175" ;
$myBike->cost = "17,999" ;

echo 'Using the display method to show the properties:<br>' . $myBike->display() . '<br>'; //parentheses () must follow method name

echo "<pre>" . var_export($myBike, TRUE) . "</pre>" ;

?>

Save & refresh browser:

Exploring an object's pseudo varibale $this

Using the display method to show the properties:
Ducati, Panigale, 1200, 175, 17,999

 

Bike::__set_state(array(
'make' => 'Ducati',
'model' => 'Panigale',
'capacity' => '1200',
'topSpeed' => '175',
'cost' => '17,999',
))

Leave a Reply