Unit 3 PHP
Unit 3 PHP
Look at the following illustration to see the difference between class and
objects:
class
Fruit
objects
Apple
Banana
Mango
When the individual objects are created, they inherit all the properties and
behaviors from the class, but each object will have different values for the
properties.
Define a Class
A class is defined by using the class keyword, followed by the name of the
class and a pair of curly braces ({}). All its properties and methods go inside the
braces:
Syntax
<?php
class Fruit {
// code goes here...
}
?>
<?php
class Fruit {
// Properties
public $name;
public $color;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
?>
Note: In a class, variables are called properties and functions are called
methods!
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.
In the example below, $apple and $banana are instances of the class Fruit:
Example
<?php
class Fruit {
// Properties
public $name;
public $color;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
echo $apple->get_name();
echo "<br>";
echo $banana->get_name();
?>
Example
<?php
class Fruit {
public $name;
function set_name($name) {
$this->name = $name;
}
}
$apple = new Fruit();
$apple->set_name("Apple");
echo $apple->name;
?>
<?php
class Fruit {
public $name;
}
$apple = new Fruit();
$apple->name = "Apple";
echo $apple->name;
?>
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);
?>
Constructor
The __construct Function
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.
Notice that the construct function starts with two underscores (__)!
We see in the example below, that using a constructor saves us from calling the
set_name() method which reduces the amount of code:
Example
<?php
class Fruit {
public $name;
public $color;
function __construct($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
Destructor
The __destruct Function
A destructor is called when the object is destructed or the script is stopped or
exited.
If you create a __destruct() function, PHP will automatically call this function
at the end of the script.
Notice that the destruct function starts with two underscores (__)!
<?php
class Fruit {
public $name;
public $color;
function __construct($name) {
$this->name = $name;
}
function __destruct() {
echo "The fruit is {$this->name}.";
}
}
Tip: As constructors and destructors helps reducing the amount of code, they
are very useful!
Access Modifiers
Properties and methods can have access modifiers which control where they can
be accessed.
<?php
class Fruit {
public $name;
protected $color;
private $weight;
}
Inheritance
Inheritance in OOP = When a class derives from another class.
The child class will inherit all the public and protected properties and methods
from the parent class. In addition, it can have its own properties and methods.
<?php
class Fruit {
public $name;
public $color;
public function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
public function intro() {
echo "The fruit is {$this->name} and the color is {$this-
>color}.";
}
}
// Strawberry is inherited from Fruit
class Strawberry extends Fruit {
public function message() {
echo "Am I a fruit or a berry? ";
}
}
$strawberry = new Strawberry("Strawberry", "red");
$strawberry->message();
$strawberry->intro();
?>
<?php
class Fruit {
public $name;
public $color;
public function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
protected function intro() {
echo "The fruit is {$this->name} and the color is {$this-
>color}.";
}
}
In the example above we see that if we try to call a protected method (intro())
from outside the class, we will receive an error.
Example
<?php
class Fruit {
public $name;
public $color;
public function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
protected function intro() {
echo "The fruit is {$this->name} and the color is {$this-
>color}.";
}
}
Look at the example below. The __construct() and intro() methods in the child
class (Strawberry) will override the __construct() and intro() methods in the
parent class (Fruit):
Example
<?php
class Fruit {
public $name;
public $color;
public function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
public function intro() {
echo "The fruit is {$this->name} and the color is {$this-
>color}.";
}
}
Example
<?php
final class Fruit {
// some code
}
Example
<?php
class Fruit {
final public function intro() {
// some code
}
}
Class Constants
Class constants can be useful if you need to define some constant data within a
class.
A class constant is declared inside a class with the const keyword.
We can access a constant from outside the class by using the class name
followed by the scope resolution operator (::) followed by the constant name,
like here:
Example
<?php
class Goodbye {
const LEAVING_MESSAGE = "Thank you for visiting W3Schools.com!";
}
echo Goodbye::LEAVING_MESSAGE;
?>
Or, we can access a constant from inside the class by using the self keyword
followed by the scope resolution operator (::) followed by the constant name,
like here:
Example
<?php
class Goodbye {
const LEAVING_MESSAGE = "Thank you for visiting W3Schools.com!";
public function byebye() {
echo self::LEAVING_MESSAGE;
}
}
Syntax
<?php
abstract class ParentClass {
abstract public function someMethod1();
abstract public function someMethod2($name, $color);
abstract public function someMethod3() : string;
}
?>
When inheriting from an abstract class, the child class method must be defined
with the same name, and the same or a less restricted access modifier. So, if
the abstract method is defined as protected, the child class method must be
defined as either protected or public, but not private. Also, the type and number
of required arguments must be the same. However, the child classes may have
optional arguments in addition.
So, when a child class is inherited from an abstract class, we have the following
rules:
The child class method must be defined with the same name and it
redeclares the parent abstract method
The child class method must be defined with the same or a less restricted
access modifier
The number of required arguments must be the same. However, the child
class may have optional arguments in addition
Example
<?php
// Parent class
abstract class Car {
public $name;
public function __construct($name) {
$this->name = $name;
}
abstract public function intro() : string;
}
// Child classes
class Audi extends Car {
public function intro() : string {
return "Choose German quality! I'm an $this->name!";
}
}
Clone Keyword
Create a copy of an object:
<?php
class MyClass {
public $color;
public $amount;
}
MyClass Object
(
[color] =>red
[amount] => 5
)
If any of the properties was a reference to another variable or object, then only
the reference is copied. Objects are always passed by reference, so if the
original object has another object in its properties, the copy will point to the
same object. This behavior can be changed by creating a __clone() method in
the class.
<?php
class MyClass {
public $amount;
}
Introspection in PHP:
Introspection in PHP offers the useful ability to examine an object's characteristics,
such as its name, parent class (if any) properties, classes, interfaces, and methods.
PHP offers a large number of functions that you can use to accomplish the task.
The following are the functions to extract basic information about classes such as
their name, the name of their parent class and so on.
In-built functions in PHP Introspection :
Function Description
class_exists() Checks whether a class has been defined.
et_class() Returns the class name of an object.
get parent_class() Returns the class name of a Return object's parent class.
is_subclass_of() Checks whether an object has a given parent class.
get_declared_classes() Returns a list of all declared classes.
get_class_methods() Returns the names of the class methods.
get_class_vars() Returns the default properties of a class
interface_exists() Checks whether the interface is defined.
method_exists() Checks whether an object defines a method.
<?php
if(class_exists('cwipedia'))
{
$ob=new cwipedia();
echo "This is cwipedia.in";
}
else
{
echo "Not exist";
}
?>
Output: Not exist
<?php
classcwipedia
{
//decl
}
if(class_exists('cwipedia'))
{
$ob=new cwipedia();
echo "This is cwipedia.in";
}
else
{
echo "Not exist";
}
?>
Serialization in PHP:
Serialization is a technique used by programmers to preserve their working
data in a format that can later be restored to its previous form.
Serialize():
The serialize() converts a storable representation of a value.
The serialize() function accepts a single parameter which is the data we
want to serialize and returns a serialized string
A serialize data means a sequence of bits so that it can be stored in a file, a
memory buffer, or transmitted across a network connection link. It is useful
for storing or passing PHP values around without losing their type and
structure.
Syntax:
serialize(value);
unserialize():
unserialize() can use string to recreate the original variable values i.e.
converts actual data from serialized data.
Syntax:
unserialize(string);
Example:
<?php
$a=array('Shivam','Rahul','Vilas');
$s=serialize($a);
print_r($s);
$s1=unserialize($s);
echo "<br>";
print_r($s1);
?>
Output:
a:3:{i:0;s:6:"Shivam";i:1;s:5:"Rahul";i:2;s:5:"Vilas";}
Array ( [0] =>Shivam [1] => Rahul [2] => Vilas )