Objects in PHP
Define Objects
Classes are nothing without objects! We can create multiple
objects from a class. Each object has all the properties and methods defined in
the class, but they will have different property values.
Objects of a class are created using the new
keyword.
In the example below, $apple and $banana are instances of the
class Fruit:
Syntax
To declare an object of a class
we need to use new statement
class myclass
{
..
..
}
$obj=new myclass;
Example
<?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 $apple->get_name();
echo "<br>";
echo $banana->get_name();
?>
Output:
Apple
Banana
In the example below, we add two more methods to class Fruit, for
setting and getting the $color property:
Example
<?php
class Fruit {
//
Properties
public $name;
public $color;
//
Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
function set_color($color) {
$this->color = $color;
}
function get_color() {
return $this->color;
}
}
$apple = new Fruit();
$apple->set_name('Apple');
$apple->set_color('Red');
echo "Name:
" .
$apple->get_name();
echo "<br>";
echo "Color:
" .
$apple->get_color();
?>
Output:
Name: Apple
Color: Red
PHP - The $this Keyword
The $this keyword refers to the current object, and is only
available inside methods.
Look at the following example:
Example
<?php
class Fruit {
public $name;
}
$apple = new Fruit();
?>
So, where can we change the value of the $name property? There are
two ways:
1. Inside the class (by adding a set_name() method and use $this):
Example
<?php
class Fruit {
public $name;
function set_name($name) {
$this->name = $name;
}
}
$apple = new Fruit();
$apple->set_name("Apple");
echo $apple->name;
?>
Output:
Apple
2. Outside the class (by directly changing the property value):
Example
<?php
class Fruit {
public $name;
}
$apple = new Fruit();
$apple->name = "Apple";
echo $apple->name;
?>
Output:
Apple
PHP - instanceof
You can use the instanceof
keyword
to check if an object belongs to a specific class:
Example
<?php
$apple = new Fruit();
var_dump($apple instanceof Fruit);
?>
Output:
bool(true)
Comments
Post a Comment