Object Oriented Programming With PHP
Object Oriented Programming With PHP
Summary
Classes
and objects
Methods and properties Scope Inheritance Static methods and properties Constants
Abstraction
and interfaces
Summary (2)
Overloading Object Iteration Object Cloning Serialization Namespaces Autoloading Classes
Classes in PHP
Declaring of a class
Classes in PHP
Class
definition begins with the class keyword, followed by its name and methods class name Method and properties list name
and body
class A { function foo () { new object echo Create "foo here!"; of class A } } $myFirstObject = new A(); $myFirstObject->foo(); // prints out "foo here!";
Constructors
Each class
class A { function __construct ($bar) { echo $bar; } function foo () { echo "foo here!"; } } $myFirstObject = new A('test'); // print 'test'
All parameters of the creating of the object are passed to the constructor
Properties
The $this variable points to the current object called execution context
More Properties
Class
world
class A { var $bar = 'default value'; } $obj = new A; echo $obj->bar;
$this
is
class A { var $bar; function __construct ($bar) { $this->bar = $bar; } function myPrint () { echo $this->bar; } } $myFirstObject = new A('test'); $myFirstObject->myPrint(); // prints 'test' $anotherObject = new A('foo'); $anotherObject ->myPrint(); // prints 'foo';
Can be used to access methods too
Destructors
Each class
Must be public
class A { function __construct ($name) { $this->fp = fopen ($name, 'r'); } function __destruct () { fclose($this->fp); } } $myFirstObject = new A('test');
Scope
Each method and property has a scope It defines who can access it
Scope Example
class A { private $bar; public function __construct ($bar) { $this->bar = $bar; } public The function myPrint () { so $bar variable is private echo $this->bar; only the object can access it } The myPrint method is }
$myFirstObject = new A('test'); $myFirstObject->myPrint(); // prints 'test' // this will not work: echo $myFirstObject->bar;
Inheritance
A class can inherit (extend) another class It inherits all its methods and properties
class A { public $bar = 'test'; public function example () { } } class B extends A { } $obj = new B(); echo $obj->bar; //prints 'test' //calls the A-class function $obj->example();
Protected Scope
Method or property, declared as protected can be accessed in classes that inherit it, but cannot be accessed from the outside world
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
used to access object's methods and properties, the :: (double colon) is used to change scope
Scope Resolution Operator
parent::
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';
class A { public static $myVariable; public static function myPrint() { echo self::$myVariable; } } A::$myVariable = 'test'; A::myPrint();
Class Constants
Constants in PHP usually are declared with the define function Constants can be defined in class Differ from normal variables no need for $ symbol to declare and access Declared with the const keyword Value must be supplied with the declaration Accessed with scope operator (::)
Class Constants
Example of a class constant
class A { const myConstant = 'value'; public function showConstant() { echo self::myConstant; } } echo A::myConstant; $obj = new A(); $obj->showConstant();
Abstraction
Classes, defined as abstract, cannot have instances (cannot create object of this class) Abstract class must have at least one abstract method Abstract methods do not have implementation (body) in the class
Only signature
The class must be inherited The child class must implement all abstract methods
Cannot increase visibility
Abstraction Example
abstract class AbstractClass { abstract protected function getValue(); abstract public function getValue2($prefix); public function printOut () { echo $this->getValue(); }
} class Class1 extends AbstractClass { protected function getValue (){ return "Class1"; } public function getValue2($prefix) { return $prefix."NAC1"; } }
Interfaces
Object interfaces allow you to specify what methods a child class must implement
Declared with the interface keyword
Similar to abstract class Interface can have only public methods No method in interface can have implementation
Interfaces are inherited with the implements keyword (instead of extends) One class may implement multiple interfaces, if they do not have methods with same names
Interface Example
interface iTemplate { public function set ($name, $value); public function getHTML($template); } class Template implements iTemplate { private $vars = array(); public function set ($name, $value) { $this->vars[$name] = $value; } public function getHTML($template) { foreach($this->vars as $name=>$value) { $template = str_replace( '{'.$name.'}', $value, $template); } return $template; } }
Overloading
Overloading in PHP provides the means to dynamically create members and methods via set of "magical" methods
Invoked with interacting with members or methods that have not been declared or are not visible in the current scope All of the magic methods must be declared as public None of the magic functions can be called with arguments, passed by reference
Overloading Methods
All overloading
methods are invoked when accessing variable or method that is not declared or is inaccessible $value) when writing
__set($name, __get
__isset
function
__unset
function
Overloading Methods
PHP "overloading" is a lot different from most languages "overloading" Usually it means the ability to declare two methods with different sets of parameters but same names
Object Iteration
PHP provides
Object Iteration
To take object iteration a step further, you can implement one of the PHP interfaces Provided by the Standard PHP Library Allows the objects to decide what to show and what not
Object Cloning
An object can be cloned with the clone
keyword
$obj1 = new A(); $obj2 = clone $obj1;
a copy of an object with fully replicated properties is not always the wanted behavior
Object Cloning
A class can implement the magic method __clone which is called for the newly created object
Example: Object holding reference to resource the new object must have new references, instead of copies
Example: Object holding reference to another object that must not be copied
Serializing Objects
Serializing
Serializing Objects
serialize
($object) returns string, representing the object ($string) returns new object, that is restored from the serialized string requires the class to be defined before calling it
unserialize
unserialize
Serializing Methods
Before serializing and after unserializing PHP checks if the class has the magic methods __sleep and __wakeup
__sleep allows the class to commit pending data, cleanup or define what needs to be stored if the object is very large
Should return array with names of properties to be stored
public function __construct($server, $user, $pass, $db) { $this->server = $server; $this->user = $user; $this->pass = $pass; $this->db = $db; $this->connect(); }
private function connect () { $this->link = mysql_connect ( $this->server, $this->user, $this->pass); mysql_select_db($this->db, $this->link); } // continues on next slide
Namespaces
Namespaces in PHP are designed to resolve scope problems in large PHP libraries Simplify development in object oriented environment Clears the code no long classes names
Namespace Definition
Namespaces
Classes,
function and etc. in a namespace are automatically prefixed with the name of the namespace
So in the example we would use Project::MyTemplate to access the class Constants in namespaces are defined with const keyword, not with define
Namespaces Example
// file Project.php namespace Project; // declare base classes and etc. // file project/db.php; namespace Project::DB; // declare DB interface for work with database // file project/db/mysql.php namespace Project::DB::MySQL; // implement the DB interface for mysql // file project/db/oracle.php Namespace Project::DB::Oracle; // implement the DB interface for Oracle // somewhere in the project require "project/db/mysql.php"; $a = new Project::DB::MySQL::Connection(); Project::DB::MySQL::connect();
Using Namespaces
If new name is not specified the namespace is imported in the current context (global namespace)
use Project::DB::MySQL; $x = new MySQL::Connection(); MySQL::connect();
Even if aliased, every class and function can be accessed at any time by full name
Global Namespace
By default PHP works in the global namespace
All the project is executed there Method from the global namespace can be referred to with empty scope operator
namespace Project::Files; // this is the Project::Files::fopen function function fopen () { $f = ::fopen (); // calls global fopen }
Autoloading Classes
Usually every class is declared in separate file
In big object oriented projects on every page you may have to include dozens of files You can define __autoload function that is called when trying to access class that is not defined
It can include the necessary file for the class
Autoload Example
<? function __autoload ($class_name) { $name = "includes/".$class_name.".inc.php"; if (file_exists ($name)) include $name; else echo 'Class not found'; } ?>
cannot
Limitation of self::
Example:
class A { public static function whoami () { echo __CLASS__; } public static function test () { self::whoami(); } } class B extends A { public static function whoami () { echo __CLASS__; } } B::test(); // outputs 'A' ?!
, SEO - , , HTML, CSS, JavaScript, Photoshop free C# book, C#, Java, C# " " " cloud "
BG Coder - - online judge , ASP.NET - , , C#, .NET, ASP.NET ASP.NET MVC HTML, SQL, C#, .NET, ASP.NET MVC , iPhone, Android, WP7, PhoneGap - - C# , ,
http://academy.telerik.com
Exercises
1.
Define class Student that holds information about students: full name, course, specialty, university, email, phone. Define constructor for the class Student that takes full name as parameter. Add a method in the class Student for displaying all information about the student. Create two students and print their information. Create an interface IAnimal that represents an animal from the real world. Define the method talk() that prints the specific scream of the animal ("jaff" for dogs, "muaw" for cats, etc.).
2.
3.
4. 5.
Exercises (2)
6.
Create an abstract class Cat that has Name and implements the interface IAnimal and introduces abstract method printInfo(). Inherit from the base abstract class Cat and create subclasses Kitten and Tomcat. These classes should fully implement the IAnimal interface and define an implementation for the abstract methods from the class Cat. Create class Dog that implements IAnimal.
7.
8. 9.
Write a class TestAnimals that creates an array of animals: Tomcat, Kitten, Dog and calls their methods through IAnimal interface to ensure the classes are implemented correctly.
Exercises (3)
10.
We are given a school. In the school there are classes of students. Each class has a set of teachers. Each teacher teaches a set of disciplines. Students have name and unique class number. Classes have unique text identifier. Teachers have name and title. Disciplines have name, number of lectures and number of exercises.
Define classes for the school (School, Class, Student, Teacher, Discipline). Keep the member fields private. Add constructors and accessor methods. Write a testing class to construct and print a sample school.
Exercises (4)
11.
We need to implement a message board where visitor can read all messages, add new messages, edit and delete existing messages.
Exercises (5)
Write a class DBUtils which will be responsible for database access for the entire application. Put this class in the file db-utils.class.php. Implement the following methods:
dbConnect() connects to the MySQL database and selects Messages database getAllMessages() returns an array of Message objects containing all messages from the database addMessage($msg) inserts a message given as Message object to the database
Exercises (6)
Write a PHP script index.php which displays all messages in a table.
academy.telerik.com/.../php-schoolacademy-meeting
academy.telerik.com
facebook.com/TelerikAcademy
forums.academy.telerik.com