0% found this document useful (0 votes)
5 views

unit4B WEB

The document explains the concepts of classes and objects in PHP, detailing how to define classes, create objects, and utilize member functions. It covers constructors and destructors for initializing and cleaning up objects, as well as inheritance for extending class functionality. Examples illustrate the creation and manipulation of objects, showcasing the use of properties and methods within classes.

Uploaded by

mukilap6
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

unit4B WEB

The document explains the concepts of classes and objects in PHP, detailing how to define classes, create objects, and utilize member functions. It covers constructors and destructors for initializing and cleaning up objects, as well as inheritance for extending class functionality. Examples illustrate the creation and manipulation of objects, showcasing the use of properties and methods within classes.

Uploaded by

mukilap6
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

PHP – Classes and Objects

The concept of classes and objects is central to PHP’s object-oriented programming


methodology. A class is the template description of its objects. It includes the properties and
functions that process the properties. An object is the instance of its class. It is characterized
by the properties and functions defined in the class.

Defining a Class in PHP


To define a class, PHP has a keyword "class". Similarly, PHP provides the keyword "new" to
declare an object of any given class.

The general form for defining a new class in PHP is as follows −

<?php
class phpClass {
var $var1;
var $var2 = "constant string";

function myfunc ($arg1, $arg2) {


[..]
}
[..]
}
?>

The keyword class is followed by the name of the class that you want to define. Class name
follows the same naming conventions as used for a PHP variable. It is followed by a pair of
braces enclosing any number of variable declarations (properties) and function definitions.

Variable declarations start with another reserved keyword var, which is followed by a
conventional $variable name; they may also have an initial assignment to a constant value.
Function definitions look much like standalone PHP functions but are local to the class and
will be used to set and access object data. Functions inside a class are also called methods.

Example

Here is an example which defines a class of Book type −

class Book {

/* Member variables */
var $price;
var $title;

/* Member functions */
function setPrice($par){
$this->price = $par;
}

function getPrice(){
echo $this->price ."<br/>";
}

function setTitle($par){
$this->title = $par;
}

function getTitle(){
echo $this->title ." <br/>";
}
}

The pseudo-variable $this is available when a method is called from within an object context.
$this refers to the calling object.

The Book class has two member variables (or properties) - $title and $price. The member
variables (also sometimes called instance variables) usually have different values for each
object; like each book has a title and price different from the other.

The Book class has functions (functions defined inside the class are called methods)
setTitle() and setPrice(). These functions are called with reference to an object and a
parameter, used to set the value of title and price member variables respectively.

The Book class also has getTitle() and getPrice() methods. When called, they return the title
and price of the object whose reference is passed.

Once a class is defined, you can declare one or more objects, using new operator.

$b1 = new Book;


$b2 = new Book;

The new operator allocates the memory required for the member variables and methods of
each object. Here we have created two objects and these objects are independent of each
other and they will have their existence separately.
Each object has access to its member variables and methods with the "->" operator. For
example, the $title property of b1 object is "$b1->title" and to call setTitle() method, use the
"$b1->setTitle()" statement.

To set the title and price of b1 object,

$b1->setTitle("PHP Programming");
$b1->setPrice(450);

Similarly, the following statements fetch the title and price of b1 book −

echo $b1->getPrice();
echo $b1->getTitle();

Example

Given below is the complete PHP script that defines Book class, declares two objects and
calls the member functions.

Open Compiler
<?php
class Book {

/* Member variables */
var $price;
var $title;

/* Member functions */
function setPrice($par){
$this->price = $par;
}

function getPrice(){
echo $this->price ."\n";
}

function setTitle($par){
$this->title = $par;
}

function getTitle(){
echo $this->title ."\n";
}
}

$b1 = new Book;


$b2 =new Book;

$b1->setTitle("PHP Programming");
$b1->setPrice(450);
$b2->setTitle("PHP Fundamentals");
$b2->setPrice(275);
$b1->getTitle();
$b1->getPrice();
$b2->getTitle();
$b2->getPrice();
?>
It will produce the following output −

PHP Programming
450
PHP Fundamentals
275

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:

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();
?>

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();
?>

Defining PHP Classes


The general form for defining a new class in PHP is as follows −

<?php
class phpClass {
var $var1;
var $var2 = "constant string";

function myfunc ($arg1, $arg2) {


[..]
}
[..]
}
?>

Here is the description of each line −

 The special form class, followed by the name of the class that you want to define.
 A set of braces enclosing any number of variable declarations and function
definitions.
 Variable declarations start with the special form var, which is followed by a
conventional $ variable name; they may also have an initial assignment to a constant
value.
 Function definitions look much like standalone PHP functions but are local to the
class and will be used to set and access object data.

Example

Here is an example which defines a class of Books type −

<?php
class Books {
/* Member variables */
var $price;
var $title;

/* Member functions */
function setPrice($par){
$this->price = $par;
}

function getPrice(){
echo $this->price ."<br/>";
}

function setTitle($par){
$this->title = $par;
}

function getTitle(){
echo $this->title ." <br/>";
}
}
?>

The variable $this is a special variable and it refers to the same object ie. itself.

Creating Objects in PHP


Once you defined your class, then you can create as many objects as you like of that class
type. Following is an example of how to create object using new operator.

$physics = new Books;


$maths = new Books;
$chemistry = new Books;

Here we have created three objects and these objects are independent of each other and they
will have their existence separately. Next we will see how to access member function and
process member variables.
Calling Member Functions
After creating your objects, you will be able to call member functions related to that object.
One member function will be able to process member variable of related object only.

Following example shows how to set title and prices for the three books by calling member
functions.

$physics->setTitle( "Physics for High School" );


$chemistry->setTitle( "Advanced Chemistry" );
$maths->setTitle( "Algebra" );

$physics->setPrice( 10 );
$chemistry->setPrice( 15 );
$maths->setPrice( 7 );

Now you call another member functions to get the values set by in above example −

$physics->getTitle();
$chemistry->getTitle();
$maths->getTitle();
$physics->getPrice();
$chemistry->getPrice();
$maths->getPrice();

This will produce the following result −

Physics for High School


Advanced Chemistry
Algebra
10
15
7

PHP – Constructor and Destructor

As in most of the object-oriented languages, you can define a constructor function in a class
in PHP also. When you declare an object with the new operator, its member variables are not
assigned any value. The constructor function is used to initialize every new object at the time
of declaration. PHP also supports having a destructor function that destroys the object from
the memory as it no longer has any reference.

The __construct() Function


PHP provides a __construct() function that initializes an object.
__construct(mixed ...$values = ""): void

The constructor method inside a class is called automatically on each newly created object.
Note that defining a constructor is not mandatory. However, if present, it is suitable for any
initialization that the object may need before it is used.

You can pass as many as arguments you like into the constructor function. The __construct()
function doesn’t have any return value.

Let us define a constructor in the Book class used in the previous chapter

Open Compiler
<?php
class Book {

/* Member variables */
var $price;
var $title;

/*Constructor*/
function __construct(){
$this->title = "PHP Fundamentals";
$this->price = 275;
}

/* Member functions */
function getPrice() {
echo "Price: $this->price \n";
}

function getTitle(){
echo "Title: $this->title \n";
}
}

$b1 = new Book;


$b1->getTitle();
$b1->getPrice();
?>

It will produce the following output −

Title: PHP Fundamentals


Price: 275

Parameterized Constructor
The member variables of $b1 have been initialized without having to call setTitle() and
setPrice() methods, because the constructor was called as soon as the object was declared.
However, this constructor will be called for each object, and hence each object has the same
values of title and price properties.

To initialize each object with different values, define the __construct() function with
parameters.
Change the definition of __construct() function to the following −

function __construct($param1, $param2) {


$this->title = $param1;
$this->price = $param2;
}

To initialize the object, pass values to the parameters inside a parenthesis in the declaration.

$b1 = new Book("PHP Fundamentals", 375);

Example

Now, you can have each object with different values to the member variables.

Open Compiler
<?php
class Book {

/* Member variables */
var $price;
var $title;

/*Constructor*/
function __construct($param1, $param2) {
$this->title = $param1;
$this->price = $param2;
}

/* Member functions */
function getPrice(){
echo "Price: $this->price \n";
}

function getTitle(){
echo "Title: $this->title \n";
}
}

$b1 = new Book("PHP Fundamentals", 375);


$b2 = new Book("PHP Programming", 450);

$b1->getTitle();
$b1->getPrice();
$b2->getTitle();
$b2->getPrice();
?>

It will produce the following output −

Title: PHP Fundamentals


Price: 375
Title: PHP Programming
Price: 450
Constructor Overloading
Method overloading is an important concept in object-oriented programming, where a class
may have more than one definitions of constructor, each having different number of
arguments. However, PHP doesn’t support method overloading. This limitation may be
overcome by using arguments with default values in the constructor function.

Change the __construct() function to the following −

function __construct($param1="PHP Basics", $param2=380) {


$this->title = $param1;
$this->price = $param2;
}

Now, declare an object without passing parameters, and the other with parameters. One
without parameters will be initialized with default arguments, the other with the values
passed.

$b1 = new Book();


$b2 = new Book("PHP Programming", 450);

It will produce the following output −

Title: PHP Basics


Price: 380
Title: PHP Programming
Price: 450

Type Declaration in Constructor


Since PHP (version 7.0 onwards) allows scalar type declarations for function arguments, the
__construct() function may be defined as −

function __construct(string $param1="PHP Basics", int $param2=380) {


$this->title = $param1;
$this->price = $param2;
}

In the earlier versions of PHP, using the name of class to define a constructor function was
allowed, but this feature has been deprecated since PHP version 8.0.

Advantages of using Constructors:

 Constructors provides the ability to pass parameters which are helpful in automatic
initialization of the member variables during creation time .
 The Constructors can have as many parameters as required and they can be defined
with the default arguments.
 They encourage re-usability avoiding re-initializing whenever instance of the class is
created .
 You can start session in constructor method so that you don’t have to start in all the
functions everytime.
 They can call class member methods and functions.
 They can call other Constructors even from Parent class.

The __destruct() Function


PHP also has a __destructor() function. It implements a destructor concept similar to that of
other object-oriented languages, as in C++. The destructor method will be called as soon as
there are no other references to a particular object.

__destruct(): void

The __destruct() function doesn’t have any parameters, neither does it have any return value.
The fact that the __destruct() function is automatically called when any object goes out of
scope, can be verified by putting var_dump($this) inside the function.

As mentioned above, $this carries the reference to the calling object, the dump shows that the
member variables are set to NULL

Add destructor function in the Book class as follows −

function __destruct() {
var_dump($this);
echo "object destroyed";
}

As the program exits, the following output will be displayed −

object(Book)#1 (2) {
["price"]=>
NULL
["title"]=>
NULL
}
object destroyed

Advantages of destructors:

 Destructors give chance to objects to free up memory allocation , so that enough


space is available for new objects or free up resources for other tasks.
 It effectively makes programs run more efficiently and are very useful as they carry
out clean up tasks.
PHP – Inheritance

Inheritance is one of the fundamental principles of object-oriented programming


methodology. Inheritance is a software modelling approach that enables extending the
capability of an existing class to build new class instead of building from scratch.

PHP provides all the functionality to implement inheritance in its object model. Incorporating
inheritance in PHP software development results in code reuse, remove redundant code
duplication and logical organization.

Imagine that you need to design a new class whose most of the functionality already well
defined in an existing class. Inheritance lets you to extend the existing class, add or remove
its features and develop a new class. In fact, PHP has the "extends" keyword to establish
inheritance relationship between existing and new classes.

class newclass extends oldclass {


...
...
}

Inheritance comes into picture when a new class (henceforth will be called inherited class,
sub class, child class, etc.) possesses "IS A" relationship with an existing class (which will be
called base class, super class, parent class, etc.).

In PHP, when a new class is defined by extending another class, the subclass inherits the
public and protected methods, properties and constants from the parent class. You are free to
override the functionality of an inherited method, otherwise it will retain its functionality as
defined in the parent class.

Example
Take a look at the following example −

Open Compiler
<?php
class myclass {
public function hello() {
echo "Hello from the parent class" . PHP_EOL;
}
public function thanks() {
echo "Thank you from parent class" . PHP_EOL;
}
}
class newclass extends myclass {
public function thanks() {
echo "Thank you from the child class" . PHP_EOL;
}
}

# object of parent class


$obj1 = new myclass;
$obj1->hello();
$obj1->thanks();

# object of child class


$obj2 = new newclass;
$obj2->hello();
$obj2->thanks();
?>

It will produce the following output −

Hello from the parent class


Thank you from parent class
Hello from the parent class
Thank you from the child class

As mentioned before, the child class inherits public and protected members (properties and
methods) of the parent. The child class may introduce additional properties or methods.

In the following example, we use the Book class as the parent class. Here, we create an
ebook class that extends the Book class. The new class has an additional property – format
(indicating ebook’s file format – EPUB, PDF, MOBI etc). The ebook class defines two new
methods to initialize and output the ebbok data – getebook() and dispebook() respectively.

Example
The complete code of inheritance example is given below −

Open Compiler
<?php
class Book {

/* Member variables */
protected int $price;
protected string $title;

public function getbook(string $param1, int $param2) {


$this->title = $param1;
$this->price = $param2;
}
public function dispbook() {
echo "Title: $this->title Price: $this->price \n";
}
}

class ebook extends Book {


private string $format;
public function getebook(string $param1, int $param2, string $param3)
{
$this->title = $param1;
$this->price = $param2;
$this->format = $param3;
}
public function dispebook() {
echo "Title: $this->title Price: $this->price\n";
echo "Format: $this->format \n";
}
}
$eb = new ebook;
$eb->getebook("PHP Fundamentals", 450, "EPUB");
$eb->dispebook();
?>

The browser output is as shown below −

Title: PHP Fundamentals Price: 450


Format: EPUB

If you take a closer look at the getebook() function, the first two assignment statements are in
fact there getbook() function, which the ebook class has inherited. Hence, we can call it with
parent keyword and scope resolution operator.

Change the getebook() function code with the following −

public function getebook(string $param1, int $param2, string $param3) {


parent::getbook($param1, $param2);
$this->format = $param3;
}

Similarly, the first echo statement in dispebook() function is replaced by a call to the
dispbook() function in parent class −

public function dispebook() {


parent::dispbook();
echo "Format: $this->format<br/>";
}
Constructor in Inheritance
The constructor in the parent class constructor is inherited by the child class but it cannot be
directly called in the child class if the child class defines a constructor.

In order to run a parent constructor, a call to parent::__construct() within the child


constructor is required.

Example

Take a look at the following example −

Open Compiler
<?php
class myclass{
public function __construct(){
echo "This is parent constructor". PHP_EOL;
}
}
class newclass extends myclass {
public function __construct(){
parent::__construct();
echo "This is child class destructor" . PHP_EOL;
}
}
$obj = new newclass();
?>

It will produce the following output −

This is parent constructor


This is child class destructor

However, if the child does not have a constructor, then it may be inherited from the parent
class just like a normal class method (if it was not declared as private).

Example

Take a look at the following example −

Open Compiler
<?php
class myclass{
public function __construct(){
echo "This is parent constructor". PHP_EOL;
}
}
class newclass extends myclass{ }
$obj = new newclass();
?>

It will produce the following output −


This is parent constructor

PHP doesn’t allow developing a class by extending more than one parents. You can have
hierarchical inheritance, wherein class B extends class A, class C extends class B, and so
on. But PHP doesn’t support multiple inheritance where class C tries to extend both class A
and class B. We can however extend one class and implement one or more interfaces.

PHP | Interface
An Interface allows the users to create programs, specifying the public methods that a class
must implement, without involving the complexities and details of how the particular
methods are implemented. It is generally referred to as the next level of abstraction. It
resembles the abstract methods, resembling the abstract classes. An Interface is defined just
like a class is defined but with the class keyword replaced by the interface keyword and just
the function prototypes. The interface contains no data variables. The interface is helpful in a
way that it ensures to maintain a sort of metadata for all the methods a programmer wishes to
work on.

Creating an Interface

Following is an example of how to define an interface using the interface keyword.

<?php

interface MyInterfaceName {
public function methodA();
public function methodB();
}

?>

Few characteristics of an Interface are:

 An interface consists of methods that have no implementations, which means the


interface methods are abstract methods.
 All the methods in interfaces must have public visibility scope.
 Interfaces are different from classes as the class can inherit from one class only
whereas the class can implement one or more interfaces.

To implement an interface, use the implements operator as follows:

<?php

class MyClassName implements MyInterfaceName{


public function methodA() {

// method A implementation
}
public function methodB(){

// method B implementation
}
}

?>

Concrete Class: The class which implements an interface is called the Concrete Class. It
must implement all the methods defined in an interface. Interfaces of the same name can’t be
implemented because of ambiguity error. Just like any class, an interface can be extended
using the extends operator as follows:

<?php

interface MyInterfaceName1{

public function methodA();

interface MyInterfaceName2 extends MyInterfaceName1{

public function methodB();


}

?>

Example:

<?php

interface MyInterfaceName{

public function method1();


public function method2();

class MyClassName implements MyInterfaceName{

public function method1(){


echo "Method1 Called" . "\n";
}

public function method2(){


echo "Method2 Called". "\n";
}
}

$obj = new MyClassName;


$obj->method1();
$obj->method2();
?>
Output:
Method1 Called
Method2 Called

Advantages of PHP Interface

 An interface allows unrelated classes to implement the same set of methods,


regardless of their positions in the class inheritance hierarchy.
 An interface can model multiple inheritances because a class can implement more
than one interface whereas it can extend only one class.
 The implementation of an inheritance will save the caller from full implementation of
object methods and focus on just he objects interface, therefore, the caller interface
remains unaffected.

PHP – Abstract Classes

The list of reserved words in PHP includes the "abstract" keyword. When a class is defined
with the "abstract" keyword, it cannot be instantiated, i.e., you cannot declare a new object of
such a class. An abstract class can be extended by another class.

abstract class myclass {


// class body
}

As mentioned above, you cannot declare an object of this class. Hence, the following
statement −

$obj = new myclass;

will result in an error message as shown below −

PHP Fatal error: Uncaught Error: Cannot instantiate abstract class myclass

An abstract class may include properties, constants or methods. The class members may be of
public, private or protected type. One or more methods in a class may also be defined as
abstract.

If any method in a class is abstract, the class itself must be an abstract class. In other words, a
normal class cannot have an abstract method defined in it.

This will raise an error −

class myclass {
abstract function myabsmethod($arg1, $arg2);
function mymethod() #this is a normal method {
echo "Hello";
}
}
The error message will be shown as −

PHP Fatal error: Class myclass contains 1 abstract method


and must therefore be declared abstract

You can use an abstract class as a parent and extend it with a child class. However, the child
class must provide concrete implementation of each of the abstract methods in the parent
class, otherwise an error will be encountered.

Example
In the following code, myclass is an abstract class with myabsmethod() as an abstract
method. Its derived class is mynewclass, but it doesn’t have the implementation of the
abstract method in its parent.

Open Compiler
<?php
abstract class myclass {
abstract function myabsmethod($arg1, $arg2);
function mymethod() {
echo "Hello";
}
}
class newclass extends myclass {
function newmethod() {
echo "World";
}
}
$m1 = new newclass;
$m1->mymethod();
?>

The error message in such a situation is −

PHP Fatal error: Class newclass contains 1 abstract method and must
therefore be declared abstract or implement the remaining
methods (myclass::myabsmethod)

It indicates that newclass should either implement the abstract method or it should be
declared as an abstract class.

Example
In the following PHP script, we have marks as an abstract class with percent() being an
abstract method in it. Another student class extends the marks class and implements its
percent() method.

Open Compiler
<?php
abstract class marks {
protected int $m1, $m2, $m3;
abstract public function percent(): float;
}

class student extends marks {


public function __construct($x, $y, $z) {
$this->m1 = $x;
$this->m2 = $y;
$this->m3 = $z;
}
public function percent(): float {
return ($this->m1+$this->m2+$this->m3)*100/300;
}
}

$s1 = new student(50, 60, 70);


echo "Percentage of marks: ". $s1->percent() . PHP_EOL;
?>

It will produce the following output −

Percentage of marks: 60

Difference between Interface and Abstract Class in PHP


The concept of abstract class in PHP is very similar to interface. However, there are a couple
of differences between an interface and an abstract class.

Abstract class Interface


Use abstract keyword to define abstract
Use interface keyword to define interface
class
Abstract class cannot be instantiated Interface cannot be instantiated.
Abstract class may have normal and Interface must declare the methods with arguments
abstract methods and return types only and not with any body.
Abstract class is extended by child Interface must be implemented by another class,
class which must implement all abstract which must provide functionality of all methods in
methods the interface.
Can have public, private or protected
Properties cannot be declared in interface
properties
PHP – Traits

In PHP, a class can inherit only from one parent class, multiple inheritance is not defined in
PHP. Traits in PHP have been introduced to overcome this limitation. You can define one or
more method in a trait, which can be reused freely in various independent classes.

Syntax
The "trait" keyword is used as per the following syntax −

trait mytrait {
function method1() {
/*function body*/
}

function method2() {
/*function body*/
}
}

To be able to call the methods in a trait, it needs to made available to another class with use
keyword.

Example
A Trait is similar to a class, but only intended to group functionality in a fine-grained and
consistent way. It is not possible to instantiate a Trait on its own.

Open Compiler
<?php
trait mytrait {
public function hello() {
echo "Hello World from " . __TRAIT__ . "";
}
}
class myclass {
use mytrait;
}
$obj = new myclass();
$obj->hello();
?>

It will produce the following output −

Hello World from mytrait


Example
A trait can be used in more than one classes. The following example has a mytrait with avg()
function int it. It is used inside a marks class. The percent() method internally calls the avg()
function from the trait.

Take a look at the following example −

Open Compiler
<?php
trait mytrait {
function avg($x, $y) {
return ($x+$y)/2;
}
}
class marks {
use mytrait;
private int $m1, $m2;
function __construct($x, $y) {
$this->m1 = $x;
$this->m2 = $y;
}
function percent():float {
return $this->avg($this->m1, $this->m2);
}
}
$obj = new marks(50, 60);
echo "percentage: " . $obj->percent();
?>

It will produce the following output −

percentage: 55

Using Multiple Traits


A class can use more than one traits. Here we have two traits with one function each
performing addition and multiplication of two numbers. Both are used inside a third class.

Open Compiler
<?php
trait addition {
function add($x, $y) {
return $x+$y;
}
}

trait multiplication {
function multiply($x, $y) {
return $x*$y;
}
}

class numbers {
use addition, multiplication;
private int $m1, $m2;
function __construct($x, $y) {
$this->m1 = $x;
$this->m2 = $y;
}
function calculate():array {
$arr = [$this->add($this->m1, $this->m2), $this->multiply($this-
>m1, $this->m2)];
return $arr;
}
}

$obj = new numbers(50, 60);


$res = $obj->calculate();
echo "Addition: " . $res[0] . PHP_EOL;
echo "Multiplication: " . $res[1] . PHP_EOL;
?>

It will produce the following output −

Addition: 110
Multiplication: 3000

Overriding Trait Function


When a class uses a certain trait, its function are available to it just as a child class inherits the
parent methods. The trait function may also be overridden.

Open Compiler
<?php
trait mytrait {
public function sayHello() {
echo 'Hello World!';
}
}

class myclass {
use mytrait;
public function sayHello() {
echo 'Hello PHP!';
}
}

$o = new myclass();
$o->sayHello();
?>

It will produce the following output −

Hello PHP!

The "insteadof" Keyword


Sometimes, more two traits might have same name of the function. Hence, using them in a
class creates ambiguous situation. PHP provides insteadof keyword to tell the parser function
from which trait you intend to use.

Open Compiler
<?php
trait mytrait {
public function sayHello() {
echo 'Hello World!';
}
}

trait newtrait {
public function sayHello() {
echo 'Hello PHP!';
}
}

class myclass {
use mytrait, newtrait{
newtrait::sayHello insteadof mytrait;
}
}

$o = new myclass();
$o->sayHello();
?>

It will produce the following output −

Hello PHP!

Aliasing a Trait Function


If you want to be able to call functions from both traits even if they have function with same
name, a workaround is to specify an alias name to one of them.

Example

In the following example, we will call sayHello() from mytrait as hello() −

Open Compiler
<?php
trait mytrait {
public function sayHello() {
echo 'Hello World!' . PHP_EOL;
}
}

trait newtrait {
public function sayHello() {
echo 'Hello PHP!' . PHP_EOL;
}
}
class myclass {
use mytrait, newtrait{
mytrait::sayHello as hello;
newtrait::sayHello insteadof mytrait;
}
}

$o = new myclass();
$o->hello();
$o->sayHello();
?>

It will produce the following output −

Hello World!
Hello PHP!

You might also like