09_PHP_Lecture
09_PHP_Lecture
OOPConsultancy
with PHP
web Engineering ||
winter 2017
wahidullah Mudaser Lecture 09
[email protected]
OOP in PHP
OUTLINE
Classes and objects
Methods and properties
Scope
Inheritance
Static methods and properties
Constants
Abstraction
interfaces
Classes and objects
The idea of Object Oriented Programming is to move the architecture of an
application closer to real world
class Dog {
… // declare methods and properties
}
class A {
var $bar = 'default value';
…
class A {
function __construct ($name) {
$this->fp = fopen ($name, 'r');
}
function __destruct () {
fclose($this->fp);
}
}
$myFirstObject = new A('test');
Destructors are automatically called when script is shutting down
Scope
class A {
protected $bar = 'test';
}
class B extends A {
public function foo () {
// this is allowed
$this->bar = 'I see it';
}
}
$obj = new B();
echo $obj->bar; //not allowed
Overriding
When a class inherits another, it can declare methods that override parent class
methods
Method names are the same
Parameters may differ
class A {
public foo() { … }
}
class B extends A {
public foo() { … }
}
Overriding Example
class A {
public foo() {
echo 'called from A';
}
}
class B extends A {
public foo() {
echo 'called from B';
}
}
$obj1 = new A();
$obj2 = new B();
$obj1->foo(); // executes A's methods
$obj2->foo(); // executes B's methods
Accessing Parent Class
As -> is used to access object's methods and properties, the :: (double colon) is
used to change scope
Scope Resolution Operator
parent:: can be used to access parent's class overridden methods
Example: call parent's constructor in the child one
Accessing Parent Class
Example of calling parent constructor
class A {
protected $variable;
public __construct() {
$this->variable = 'test';
}
}
class B extends A {
public __construct() {
parent::__construct();
echo $this->variable;
}
}
$obj1 = new B();
// prints 'test';
The static Keyword
Defining method or property as 'static' makes them accessible without needing an
instantiation of a class
Accessed with the double-colon (::) operator instead of the member (->) operator
$this is not available in static methods
Static properties and methods can also have scope defined – public, private or protected
The static Keyword
Example of static method and property
class A {
public static $myVariable;
public static function myPrint() {
echo self::$myVariable;
}
}
A::$myVariable = 'test';
A::myPrint();
echo A::myConstant;