You are on page 1of 28

CS-02: Advance Web Development in Laravel UNIT - 1

Object Oriented Programming in PHP


• The Basics
• Properties
• Class Constants
• Auto loading Classes
• Constructors and Destructors
• Visibility
• Inheritance
• Scope Resolution Operator (::)
• Static Keyword
• Class Abstraction
• Object Interfaces
• Anonymous classes
• Overloading
• ObjectIteration
• Magic Methods
• Final Keyword
• Object Cloning
• Comparing Objects
• Type Hinting
• Late Static Bindings
• Objects and references

Page 1 of 28 Study notes by : BHAVESH CHAVDA


CS-02: Advance Web Development in Laravel UNIT - 1

CONCEPT OF OOP

INTRODUCTION
Object-oriented programming is an approach to programming where objects and classes are
used. Now-a-days Java and C++ are mostly used for object-oriented programming. There
was limited scope of object-oriented programming in PHP 4, but in PHP 5, the object model
was rewritten for better performance and more features. Now PHP 5 has a full object
model.

Object
The fundamental idea behind an object-oriented language is to enclose a bundle of variables
and functions into a single unit and keep both variables and functions safe from outside
interference and misuse. Such a unit is called object which acts on data. The mechanism
that binds together data and functions are called encapsulation. This feature makes it easy
to reuse code in various projects. The functions declared in an object provides the way to
access the data. The functions of an object are called methods and all the methods of an
object have access to variables called properties.
The following picture shows the components of an object.

Member Data

Member Function

Class
In object-oriented programming, a class is a construct or prototype from which objects are
created. A class defines constituent members which enable class instances to have state and
behavior. Data field members enable a class object to maintain state and methods enable a
class object's behavior. The following picture shows the components of a class.

Object
Member Data 1
Class
Member Data 2
Member Data 1
Member Data 2

Member Function 1 Object


Member Function 2
Member Data 1
Member Data 2

Page 2 of 28 Study notes by : BHAVESH CHAVDA


CS-02: Advance Web Development in Laravel UNIT - 1

Creating classes and Instantiation

• The class definition starts with the keyword class followed by a class name, then
followed by a set of curly braces ({}) which enclose constants, variables (called
"properties"), and functions (called "methods") belonging to the class.

• A valid class name (excluding the reserved words) starts with a letter or underscore,
followed by any number of letters, numbers, or underscores.

• Class names usually begin with an uppercase letter to distinguish them from other
identifiers.

• An instance is an object that has been created from an existing class.

• Creating an object from an existing class is called instantiating the object.

• To create an object out of a class, the new keyword must be used.

• Classes should be defined prior to instantiation.

Example:

<?php
classMyclass
{
// Add property statements here
// Add the methods here
}

?>

In the following example keyword new is used to instantiate an object. Here $myobj
represents an object of the class Myclass.
Example:

<?php
$myobj=newMyClass;
?>

Page 3 of 28 Study notes by : BHAVESH CHAVDA


CS-02: Advance Web Development in Laravel UNIT - 1

Properties

• Class member variables are called properties. Sometimes they are referred as attributes
or fields.

• The properties hold specific data and related with the class in which it has been defined.

• Declaring a property in a class is an easy task, use one of the keyword public, protected,
or private followed by a normal variable declaration. If declared using var
(compatibility with PHP 4), the property will be defined as public.

o public : The property can be accessed from outside the class, either by the
script or from another class

o private : No access is granted from outside the class, either by the script or
from another class.

o protected : No access is granted from outside the class except a class that’s a
child of the class with the protected property or method.

• nowdocs ( as of PHP 5.3.0) can be used in any static data context, including property
declarations.

Example:

After an object is instantiated, you can access the property of a class using the object and
-> operator. Any member declared with keyword "private" or "protected" cannot be
accessed outside the method of the class.
<?php
classMyclass
{
public$font_size=10;
}
$f=newMyClass;
echo$f->font_size;

?>
Output:
10
Note: There is a common mistake to use more than one dollar sign when accessing
variables. In the above example there will be no $ sign before font_size (echo $f->font_size).

Page 4 of 28 Study notes by : BHAVESH CHAVDA


CS-02: Advance Web Development in Laravel UNIT - 1

After defining methods we will discuss an example with public, private and protected class
properties.

Setting Methods

• The functions which are declared in a class are called methods.

• A class method is exactly similar to PHP functions.

• Declaring a method in a class is an easy task, use one of the keyword public,
protected, or private followed by a method name.

o public : The method can be accessed from outside the class.

o private : No access is granted from outside the class.

o protected : No access is granted from outside the class except a class that’s a
child of the class with the protected property or method.

• A valid method name starts with a letter or underscore, followed by any number of
letters, numbers, or underscores.

• The method body enclosed within a pair of braces which contains codes. The
opening curly brace ( { ) indicates the beginning of the method code and the closing
curly ( } ) brace indicates the termination of the method.

• If the method is not defined by public, protected, or private then default is public.

• Can access properties and methods of the current instance using $this (Format $this-
>property) for non static property.

Example:

After an object is instantiated, you can access the method of a class using the object and -
> operator. In the following example customize_print() method will print a string with a
specific font size and color within a html paragraph element with the help of php echo
statement.

<?php
classMyclass
{
public$font_size="18px";
public$font_color="blue";
public$string_name="Harivandana College";
publicfunctioncustomize_print()

Page 5 of 28 Study notes by : BHAVESH CHAVDA


CS-02: Advance Web Development in Laravel UNIT - 1

{
echo"<p style=font-size:".$this->font_size.";color:".$this->font_color.";>".$this-
>string_name."</p>";
}
}
$f=newMyClass;
echo$f->customize_print();

?>
Output:

Harivandana College

Now change the value of font_size, font_color and the string and check what the
method custimize_print() returns.
<?php
classMyclass
{
public$font_size="18px";
public$font_color="blue";
public$string_name="Harivandana College";
publicfunctioncustomize_print()
{
echo"<p style=font-size:".$this->font_size.";color:".$this-
>font_color.";>".$this->string_name."</p>";
}
}
$f=newMyClass;
$f->font_size="20px";
$f->font_color="red";
$f->string_name="Object Oriented Programming";
echo$f->customize_print();

?>

PHP: Scope Resolution Operator (::)

In PHP, the scope resolution operator is also called "double colon" or "double dot twice" in
Hebrew. The double colon (::), is a token which allows access to static, constant, and
overridden properties or methods of a class.

Page 6 of 28 Study notes by : BHAVESH CHAVDA


CS-02: Advance Web Development in Laravel UNIT - 1

Example:

<?php
Class Book
{
Const NAME = " Let us C";
Const AUTHOR="Yashwant Kanetkar";
}
echo"Name of Book:<br>";
echoBook::NAME;
echo"<br>Name of Author:<br>";
echoBook::AUTHOR;
?>
Output:

Name of Book:
Let us C
Name of Author:
Yashwant Kanetkar

PHP: Class Constants

• A special entity that remains fixed on an individual class basis.

• Constant names are not preceded by a dollar sign ($) like a normal variable
declaration.

• Interfaces may also include constants.

• When calling a class constant using the $classname :: constant syntax, the classname
can actually be a variable.

• As of PHP 5.3, you can access a static class constant using a variable reference
(Example: className :: $varConstant).

Page 7 of 28 Study notes by : BHAVESH CHAVDA


CS-02: Advance Web Development in Laravel UNIT - 1

Define and using a constant

<?php
classMyClass
{
const constant1 ='PHP Class Constant';
functionPrintConstant()
{
echoself::constant1 ."<br>";
}
}
echoMyClass::constant1 ."<br>";
$classname="MyClass";
echo $classname::constant1 ."<br>";// As of PHP 5.3.0
$class=newMyClass();
$class->PrintConstant();
echo $class::constant1."<br>";// As of PHP 5.3.0

?>

PHP Constructor methods

• The constructor is a special built-in method, added with PHP 5, allows developers to
declare for classes.

• Constructors allow to initializing object properties ( i.e. the values of properties)


when an object is created.

• Classes which have a constructor method execute automatically when an object is


created.

• The 'construct' method starts with two underscores (__).

• The constructor is not required if you don't want to pass any property values or
perform any actions when the object is created.

• PHP only ever calls one constructor.

The general syntax for constructor declaration follows :

function __construct([argument1, argument2, ..., argumentN])


{
/* Class initialization code */
}
The type of argument1, argument2,.......,argumentN are mixed.

Page 8 of 28 Study notes by : BHAVESH CHAVDA


CS-02: Advance Web Development in Laravel UNIT - 1

Example:

<?php
// Define a class
classMyclass
{
// Declaring three private varaibles
private$font_size;
private$font_color;
private$string_value;
// Declarte construct method which accepts three parameters
function__construct($font_size,$font_color,$string_value)
{
$this->font_size=$font_size;
$this->font_color=$font_color;
$this->string_value=$string_value;
}
// Declare a method for customize print
functioncustomize_print()
{
echo"<p style=font-size:".$this->font_size.";color:".$this-
>font_color.";>".$this->string_value."</p>";
}
}
// Create a new object and passes three parameters
$f=newMyClass('20px','red','Object Oriented Programming');
// Call the method to display the string
echo$f->customize_print();

?>

PHP Destructors methods

• The destructor is the counterpart of constructor.

• A destructor function is called when the object is destroyed

• A destructor function cleans up any resources allocated to an object after the object
is destroyed.

• A destructor function is commonly called in two ways: When a script ends or


manually delete an object with
the unset() function

• The 'destructor' method starts with two underscores (__).

Page 9 of 28 Study notes by : BHAVESH CHAVDA


CS-02: Advance Web Development in Laravel UNIT - 1

The general syntax for destructor declaration follows :

function __destruct
{
/* Class initialization code */
}
The type of argument1, argument2,.......,argumentN are mixed.

PHP: Inheritance

• Inheritance is a well-established programming principle.

• Inheritance enables classes to form a hierarchy like a family tree.

• Allows subclasses to share the methods and properties (which are public or
protected) of its superclass.

• Superclass is the parent class.

• A subclass can add properties and methods.

• Inheritance allows reusing code.

Base Class

Process 1 Process 2 Process 3

Base Class

Process 4 Process 1 Process 2 Process 3

Defined in derived Accessible by the


class derived class

Page 10 of 28 Study notes by : BHAVESH CHAVDA


CS-02: Advance Web Development in Laravel UNIT - 1

Example:

In the following example subclass, 'Mysubclass' inherits all the protected properties and
public method from 'Myclass' class. In addition, we add a text-decoration attribute within
echo statement in the subclass 'Mysubclass'.

<?php
// Define a class
classMyclass
{
// Declaring three protected varaibles protected $font_size;
protected$font_color;
protected$string_value;
// Declarte construct method which accepts three parameters and the method
customize_print()
function__construct($font_size,$font_color,$string_value)
{
$this->font_size=$font_size;
$this->font_color=$font_color;
$this->string_value=$string_value;
$this->customize_print();
}
// Declare a method for customize print
publicfunctioncustomize_print()
{
echo"<p style=font-size:".$this->font_size.";color:".$this-
>font_color.";>".$this->string_value."</p>";
}
}
// Define a subclass
classMysubclassextendsMyclass
{
// Call the method customize print() and add the text decoration attribute within
echo statement
publicfunctioncustomize_print()
{
echo"<p style=font-size:".$this->font_size.";color:".$this->font_color.";text-
decoration:underline;>".$this->string_value."</p>";
}
}
// Create objects and passes parameters
$p=newMyclass('20px','red','Object Oriented Programming');
$s=newMysubclass('15px','green','Object Oriented Programming');
?>

Page 11 of 28 Study notes by : BHAVESH CHAVDA


CS-02: Advance Web Development in Laravel UNIT - 1

Auto loading Classes


- Many developers writing object-oriented applications create one PHP source file per class
definition.
- One of the having to write a long list of needed includes at the beginning of each script
(one for each class).
- The __autoload function registers any number of autoloaders, enabling for classes and
interfaces to be automatically loaded if they are currently not defined.

Example :
This example attempts to load the classes MyClass1 and MyClass2 from the files
MyClass1.php and MyClass2.php respectively.

Index.php
<?php
Function __autoload($className)
{
Include_once(“$className.php”);
}
$obj1= new MyClass1();
$obj2= new MyClass2();
?>

Abstract Classes

Abstract classes and methods are when the parent class has a named method, but need its child
class(es) to fill out the tasks.

An abstract class is a class that contains at least one abstract method. An abstract method is a
method that is declared, but not implemented in the code.

An abstract class or method is defined with the abstract keyword:

<?php
abstract class ParentClass {
abstract public function someMethod1();
abstract public function someMethod2($name, $color);
}
?>

Page 12 of 28 Study notes by : BHAVESH CHAVDA


CS-02: Advance Web Development in Laravel UNIT - 1

PHP OOP - Interfaces

Interfaces allow you to specify what methods a class should implement.

Interfaces make it easy to use a variety of different classes in the same way. When one or more
classes use the same interface, it is referred to as "polymorphism".

Interfaces are declared with the interface keyword:

<?php
interface InterfaceName {
public function someMethod1();
public function someMethod2($name, $color);
}
?>

PHP - Interfaces vs. Abstract Classes

Interface are similar to abstract classes. The difference between interfaces and abstract classes
are:

• Interfaces cannot have properties, while abstract classes can


• All interface methods must be public while abstract class methods may also be private or
protected
• All methods in an interface are abstract, so they cannot be implemented in code and the
abstract keyword is not necessary
• Classes can implement an interface while inheriting from another class at the same time

PHP - Using Interfaces

To implement an interface, a class must use the implements keyword.

A class that implements an interface must implement all of the interface's methods.

<?php
interface Animal {
public function makeSound();
}

class Cat implements Animal {


public function makeSound() {
echo "Meow";
}
}

$animal = new Cat();


$animal->makeSound();
?>

Page 13 of 28 Study notes by : BHAVESH CHAVDA


CS-02: Advance Web Development in Laravel UNIT - 1

Anonymous Class
At the most fundamental level an Anonymous Class is simply a class definition without a name. It is
defined just like any other class. In truth, they do have internally generated names so we do not
need to provide the names.
<?php
$obj= new class(){
public function show(){
echo "this is anonymous funciton example";
}
};
$obj->show();
?>

Object Iteration
From PHP 5 onwards, it is possible to iterate through list of all visible items of an object.
Iteration can be performed using foreach loop as well as iterator interface. There is
also IteratorAggregate interface in PHP, that can be used for this purpose

<?php
class myclass{
private $var;
protected $var1;
public $x, $y, $z;
public function __construct(){
$this->var="private variable";
$this->var1=TRUE;
$this->x=100;
$this->y=200;
$this->z=300;
}
public function iterate(){
foreach ($this as $key => $value) {
print "$key => $value\n";
}
}
}
$obj = new myclass();
foreach($obj as $key => $value) {
print "$key => $value\n";
}
echo "\n";
$obj->iterate();
?>

Page 14 of 28 Study notes by : BHAVESH CHAVDA


CS-02: Advance Web Development in Laravel UNIT - 1

PHP Object Cloning


Object cloning is creating a copy of an object. An object copy is created by using
the clone keyword.
When there is a need that you do not want the outer enclosing object to modify
the internal state of the object then the default PHP cloning can be used. I will
demonstrate object cloning using an example in this article.

Copy Objects by Assignment


<?php
classAnimals
{
public $name;
public $category;
}
//Creating instance of Animals class
$objAnimals = newAnimals();
//setting properties
$objAnimals->name = "Lion";
$objAnimals->category = "Wild Animal";
//Copying object
$objCopied = $objAnimals;
$objCopied->name = "Cat";
$objCopied->category = "Pet Animal"
print_r($objAnimals);
print_r($objCopied);
?>
When we change $objCopied it affects $objAnimals. The output is,
Values of object $objAnimals:
Animals Object
(
[name] => Cat
[category] => Pet Animal
)
Values of Copied object $objCopied:
Animals Object
(
[name] => Cat
[category] => Pet Animal
)

Page 15 of 28 Study notes by : BHAVESH CHAVDA


CS-02: Advance Web Development in Laravel UNIT - 1

Object Copy by clone

In the below example, we are copying objects by using PHP clone keyword. PHP’s
clone method does a shallow copy and so, any changes made in the cloned object
will not affect original object.

__clone is a magic method in PHP. Magic methods are predefined in PHP and
starts with “__” (double underscore). They are executed in response to some
events in PHP.
<?php
//Creating instance of Animals class
$objAnimals =newAnimals();
//Assigning values
$objAnimals->name ="Lion";
$objAnimals->category ="Wild Animal";
//Cloning the original object
$objCloned = clone $objAnimals;
$objCloned->name ="Elephant";
$objCloned->category ="Wild Animal";
print_r($objAnimals);
print_r($objCloned);
?>

Now we can see the difference in the output of this code.


Values of object $objAnimals:
Animals Object
(
[name] => Lion
[category] => Wild Animal
)
Values of Cloned object $objCopied:
Animals Object
(
[name] => Elephant
[category] => Wild Animal
)

Page 16 of 28 Study notes by : BHAVESH CHAVDA


CS-02: Advance Web Development in Laravel UNIT - 1

PHP Comparing Objects

Introduction
PHP has a comparison operator == using which a simple comparison of two objects variables
can be performed. It returns true if both belong to same class and values of corresponding
properties are same.
PHP's === operator compares two object variables and returns true if and only if they refer
to same instance of same class
We use following two classes for comparison of objects with these operators

Example
<?php
class test1{
private $x;
private $y;
function __construct($arg1, $arg2){
$this->x=$arg1;
$this->y=$arg2;
}
}
class test2{
private $x;
private $y;
function __construct($arg1, $arg2){
$this->x=$arg1;
$this->y=$arg2;
}
}
?>
Two objects of same class
Example
$a=new test1(10,20);
$b=new test1(10,20);
echo "two objects of same class\n";
echo "using == operator : ";
var_dump($a==$b);
echo "using === operator : ";
var_dump($a===$b);
Output
two objects of same class
using == operator : bool(true)
using === operator : bool(false)
two references of same object

Page 17 of 28 Study notes by : BHAVESH CHAVDA


CS-02: Advance Web Development in Laravel UNIT - 1

Example

$a=new test1(10,20);

$c=$a;

echo "two references of same object\n";

echo "using == operator : ";

var_dump($a==$c);

echo "using === operator : ";

var_dump($a===$c);

Output
two references of same object
using == operator : bool(true)
using === operator : bool(true)
two objects of different classes
Example
$a=new test1(10,20);
$d=new test2(10,20);
echo "two objects of different classes\n";
echo "using == operator : ";
var_dump($a==$d);
echo "using === operator : ";
var_dump($a===$d);
Output
Output shows following result

two objects of different classes


using == operator : bool(false)
using === operator : bool(false)

Page 18 of 28 Study notes by : BHAVESH CHAVDA


CS-02: Advance Web Development in Laravel UNIT - 1

PHP Magic Methods


The __construct() Method
If you define this method in your class, it’ll be called automatically when an object is
instantiated. The purpose of this method is to assign some default values to object
properties. This method is also called a constructor.

Let’s have a look at a quick example to understand how it works:

<?php
class Student {
private $name;
private $email;

public function __construct($name, $email)


{
$this->name = $name;
$this->email = $email;
}
}

$objStudent = new Student('John', 'john@tutsplus.com');


?>
In the above example, when you instantiate a new object with new
student('John','john@tutsplus.com') , it calls the __construct() method in the first place.
In the __construct() method, we’ve assigned values passed in the arguments to the object
properties.

The __destruct() Method

The __destruct() method is called a destructor, and it’s called when the object is
destroyed. Generally, it’s also called when the script is stopped or exited. The purpose of
this method is to provide an opportunity to save the object state or any other cleanups you
would want to perform.

Let’s have a look at the following example:

Page 19 of 28 Study notes by : BHAVESH CHAVDA


CS-02: Advance Web Development in Laravel UNIT - 1

<?php
classStudent {
private$name;
private$email;
publicfunction__construct($name, $email)
{
$this->name = $name;
$this->email = $email;
}
publicfunction__destruct()
{
echo'This will be called when the script is shut down...';
// save object state/other clean ups
}
}
$objStudent= newStudent('John', 'john@tutsplus.com');
?>

The __set() Method

The __set() magic method is called when you try to set data to inaccessible or non-existent
object properties. The purpose of this method is to set extra object data for which you
haven’t defined object properties explicitly.

Let’s get back to our example to understand how it works.

<?php
classStudent {
private$data= array();

publicfunction__set($name, $value)
{
$this->data[$name] = $value;
}
}

$objStudent= newStudent();

// __set() called
$objStudent->phone = '0491 570 156';
?>
As you can see in the above example, we’re trying to set the phone property, which is non-
existent. And thus, the __set() method is called. The first argument of the __set() method
is the name of the property which is being accessed, and the second argument is the value
we’re trying to set.

Page 20 of 28 Study notes by : BHAVESH CHAVDA


CS-02: Advance Web Development in Laravel UNIT - 1

The __get() Method

In the case of the __set() method example in the previous section, we discussed how to set
values for non-existent properties. The __get() method is exactly the opposite of it.
The __get() magic method is called when you try to read data from inaccessible or non-
existent object properties. The purpose of this method is to provide values to such
properties.

Let’s see how it works in action.

<?php
classStudent {
private$data= array();

publicfunction__set($name, $value)
{
$this->data[$name] = $value;
}

publicfunction__get($name)
{
If (isset($this->data[$name])) {
return$this->data[$name];
}
}
}

$objStudent= newStudent();

// __set() called
$objStudent->phone = '0491 570 156';

// __get() called
echo$objStudent->phone;
?>

The __toString() Method

The __toString() magic method allows you to define what you would like to display when
an object of the class is treated like a string. If you use echo or print on your object, and
you haven’t defined the __toString() method, it’ll give an error.

Let’s try to understand it with the following example.

Page 21 of 28 Study notes by : BHAVESH CHAVDA


CS-02: Advance Web Development in Laravel UNIT - 1

<?php
classStudent {
private$name;
private$email;

publicfunction__construct($name, $email)
{
$this->name = $name;
$this->email = $email;
}

publicfunction__toString()
{
return'Student name: '.$this->name
. '<br>'
. 'Student email: '.$this->email;
}
}

$objStudent= newStudent('John', 'john@tutsplus.com');


echo$objStudent;
?>
In the above example, when you echo the $objStudent object, it’ll call
the __toString() method. And in that method, you can decide what you would like to
display. If you hadn’t defined the __toString() method, this would have resulted in an
error!

The __call() and __callStatic() Methods

If __get() and __set() methods are called when you’re dealing with non-existent
properties, the __call() method is called when you’re trying to invoke inaccessible
methods, the methods that you haven’t defined in your class.

<?php
classStudent {
publicfunction__call($methodName, $arguments)
{
// $methodName = getStudentDetails
// $arguments = array('1')
}
}
$objStudent= newStudent();
$objStudent->getStudentDetails(1);
?>

Page 22 of 28 Study notes by : BHAVESH CHAVDA


CS-02: Advance Web Development in Laravel UNIT - 1

As you can see, we’ve called the method getStudentDetails , which is not defined, and thus
the __call() magic method is called. The first argument is the name of the method being
called, and the second argument is an array of arguments that were passed in that method.

The __callStatic() method is very similar to the __call() method; the only exception is that
it’s called when you’re trying to invoke inaccessible methods in a static context. So if you’re
trying to access any static method which is not defined, the __callStatic() function will be
called.

The __isset() and __unset() Methods

The __isset() magic method is called when you call the isset() method on inaccessible or
non-existent object properties. Let’s see how it works through an example.

<?php
classStudent {
private$data= array();

publicfunction__isset($name)
{
returnisset($this->data[$name]);
}
}

$objStudent= newStudent();
echoisset($objStudent->phone);
?>
In the above example, the phone property is not defined in the class, and thus it’ll call
the __isset() method.

On the other hand, the __unset() is a method called when you call the unset() method on
inaccessible or non-existent object properties.

The __clone() Method

If you want to duplicate an existing object, you could use the clone keyword to do that. But
after cloning, if you want to modify properties of the cloned object, you can define
the __clone() magic method in your class.

Page 23 of 28 Study notes by : BHAVESH CHAVDA


CS-02: Advance Web Development in Laravel UNIT - 1

<?php
Class Student_School {
}

classStudent {
private$name;
private$email;
private$object_student_school;

publicfunction__construct()
{
$this->object_student_school = newStudent_School();
}

publicfunction__clone()
{
$this->object_student_school = clone$this->object_student_school;
}
}

$objStudentOne= newStudent();
$objStudentTwo= clone$objStudentOne;
?>
The issue with the above approach is that it makes a shallow copy of the object while
cloning, and thus internal objects of the cloned object will not be cloned.

In the context of the above example, if you hadn’t defined the __clone() method, the
cloned object, $objStudentTwo , would still point to the same Student_School object
referenced by the $objStudentOne object. Thus, by implementing the __clone() method,
we make sure that the Student_School object is cloned along with the main object.

Static Keyword

Declaring class properties or methods as static makes them accessible without needing an
instantiation of the class. A property declared as static cannot be accessed with an
instantiated class object (though a static method can).

Page 24 of 28 Study notes by : BHAVESH CHAVDA


CS-02: Advance Web Development in Laravel UNIT - 1

Static methods and property

Because static methods are callable without an instance of the object created, the pseudo-
variable $this is not available inside the method declared as static.

<?php
class Demo {
public static $colg;
public static function aStaticMethod() {
echo “static method called”;
}
}
Demo::$colg=”harivandana college”;
Demo::aStaticMethod();
?>

Final Keyword

PHP 5 introduces the final keyword, which prevents child classes from overriding a method
by prefixing the definition with final. If the class itself is being defined final then it cannot be
extended.
<?php
class BaseClass {
public function test() {
echo "BaseClass::test() called\n";
}

final public function moreTesting() {


echo "BaseClass::moreTesting() called\n";
}
}

class ChildClass extends BaseClass {


public function moreTesting() {
echo "ChildClass::moreTesting() called\n";
}
}
// Results in Fatal error: Cannot override final method BaseClass::moreTesting()
?>

Late Static Bindings in PHP


In PHP, programs are saved and then directly run on the browser, the script is executed
through a web server and we get the output. We don’t compile PHP programs manually but
that does not mean it is never compiled. The PHP interpreter does that for you and runs it.
So there are two phases, first, compile-time and second run time. During the compile time,
the normal variables are replaced with their values but the static keywords are replaced

Page 25 of 28 Study notes by : BHAVESH CHAVDA


CS-02: Advance Web Development in Laravel UNIT - 1

only in the run time. Overriding a property in child class and creating the instance of the
child class, so to get the overridden output, the late static binding concept is used by writing
static keyword before using the property. Whenever a PHP interpreter gets the request to
compile a function. If it sees any static property, then it leaves the property pending for run
time and the property gets its value during runtime from the function it is being called. This
is called late static binding.
This feature of late static binding was introduced in PHP 5.3 and above, previous versions
will show a fatal error.
<?php
class Demo{
public static $name="Harivandana College";
public static function view(){
echo "Demo class Welcome to ".self::$name;
}
public static function viewSecond(){
static::view();
//echo $op." yes its success";
}
}
class DemoNew extends Demo{
public static function view(){
echo "welcome to ".self::$name." - Rajkot";
}
}
class DemoThree extends DemoNew{
public static function view(){
echo "welcome to ".self::$name." - munjka, rajkot";
}
}
Demo::viewSecond();
echo "<br>";
DemoNew::viewSecond();
echo "<br>";
DemoThree::viewSecond();
?>

Type Hinting
o In simple word, type hinting means providing hints to function to only accept the
given data type.
o In technical word we can say that Type Hinting is method by which we can force
function to accept the desired data type.
o In PHP, we can use type hinting for Object, Array and callable data type.

Page 26 of 28 Study notes by : BHAVESH CHAVDA


CS-02: Advance Web Development in Laravel UNIT - 1

Example 1

<?php
class a
{
public $c= "hello welcome to Harivanda";
}
//create function with class name argument
Function show($name) – built-in datatype
function display(a $a1) - user define data type
{
//call variable
echo $a1->c;
}
display(new a());
?>

Example 2

<?php
class Test1
{
public $var= "welcome to harivandana college -rajkot";
}
//create function with class name argument
function typehint(Test1 $t1)
{
//call variable
echo $t1->var;
}
//call function with call name as a argument
typehint(new Test1());
?>

Objects and references


One of the key-points of PHP 5 OOP that is often mentioned is that "objects are passed by
references by default". This is not completely true. This section rectifies that general
thought using some examples.
A PHP reference is an alias, which allows two different variables to write to the same value.
As of PHP 5, an object variable doesn't contain the object itself as value anymore. It only
contains an object identifier which allows object accessors to find the actual object. When
an object is sent by argument, returned or assigned to another variable, the different
variables are not aliases: they hold a copy of the identifier, which points to the same object.

Page 27 of 28 Study notes by : BHAVESH CHAVDA


CS-02: Advance Web Development in Laravel UNIT - 1

<?php
class myClass {
public $var;
function __construct() {
$this->var = 1;
}
function inc() {
return ++$this->var;
}
}
$a = new myClass(); //obj create
$b = $a; //obje pass as value ( both object value address are different)
total created address are 2
echo "a = ";
var_dump($a);
echo "<br>b = ";
var_dump($b);
$c = &$a; //obj pass as ref( both object value address are same) total
created address in 1 that main object address
echo "<br>c = ";var_dump($c);
$a = NULL;
echo "<br>a = ";var_dump($a);
echo "<br>b = ";var_dump($b);
echo "<br>c = ";var_dump($c);
echo "<br>b->inc: ".$b->inc();
echo "<br>b->inc: ".$b->inc();
$b = NULL;
echo "<br>b = ";var_dump($b);
?>

Page 28 of 28 Study notes by : BHAVESH CHAVDA

You might also like