PHP Knowledge Base

OOP Examples from w3schools.com

Example #11
<?php 
class Fruit {
	// Properties
	public $name;
	public $color;

	// Methods
	function set_name($name) {
		$this->name = $name;
	}
	function get_name() {
		return $this->name;
	}
}

$apple = new Fruit();
$banana = new Fruit();
$apple->set_name('Apple');
$banana->set_name('Banana');

echo "Fruit name = " . $apple->get_name();
echo "<br>";
echo "Fruit name = " . $banana->get_name();
?>

demo

Example #2: __construct Function2

A constructor allows you to initialize an object's properties upon creation of the object.

If you create a __construct() function, PHP will automatically call this function when you create an object from a class.

We see in the example below, that using a constructor saves us from calling the set_name() method which reduces the amount of code:

<?php 
class Fruit {
	public $name;
	public $color;

	function __construct($name, $color) {
		$this->name = $name; 
		$this->color = $color; 
	}
	function get_name() {
		return $this->name;
	}
	function get_color() {
		return $this->color;
	}
}

$apple = new Fruit("Apple", "red");
echo $apple->get_name();
echo "<br>";
echo $apple->get_color();
?>

demo

Example #3: __destruct Function3
<?php 
class Fruit {
	public $name;
	public $color;

	function __construct($name) {
		$this->name = $name; 
	}
	function __destruct() {
		echo "The fruit is {$this->name}."; 
	}
}

$apple = new Fruit("Apple");
?>

demo

<?php 
NULL
?>

demo