unit4B WEB
unit4B WEB
<?php
class phpClass {
var $var1;
var $var2 = "constant string";
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
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.
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.
$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->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.
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();
?>
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;
}
}
<?php
class phpClass {
var $var1;
var $var2 = "constant string";
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
<?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.
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->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();
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 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";
}
}
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 −
To initialize the object, pass values to the parameters inside a parenthesis in the declaration.
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->getTitle();
$b1->getPrice();
$b2->getTitle();
$b2->getPrice();
?>
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.
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.
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.
__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
function __destruct() {
var_dump($this);
echo "object destroyed";
}
object(Book)#1 (2) {
["price"]=>
NULL
["title"]=>
NULL
}
object destroyed
Advantages of destructors:
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.
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;
}
}
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;
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.
Similarly, the first echo statement in dispebook() function is replaced by a call to the
dispbook() function in parent class −
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();
?>
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
Open Compiler
<?php
class myclass{
public function __construct(){
echo "This is parent constructor". PHP_EOL;
}
}
class newclass extends myclass{ }
$obj = new newclass();
?>
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
<?php
interface MyInterfaceName {
public function methodA();
public function methodB();
}
?>
<?php
// 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{
?>
Example:
<?php
interface MyInterfaceName{
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.
As mentioned above, you cannot declare an object of this class. Hence, the following
statement −
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.
class myclass {
abstract function myabsmethod($arg1, $arg2);
function mymethod() #this is a normal method {
echo "Hello";
}
}
The error message will be shown as −
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();
?>
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;
}
Percentage of marks: 60
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();
?>
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();
?>
percentage: 55
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;
}
}
Addition: 110
Multiplication: 3000
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();
?>
Hello PHP!
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();
?>
Hello PHP!
Example
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();
?>
Hello World!
Hello PHP!