Advance OOP in PHP.

Slides:



Advertisements
Similar presentations
PHP functions What are Functions? A function structure:
Advertisements

Object-Oriented PHP (1)
Road Map Introduction to object oriented programming. Classes
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
OOP in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Nikolay Kostov Telerik Corporation
Review of C++ Programming Part II Sheng-Fang Huang.
CMSC 202 Interfaces. 11/20102 Classes and Methods When a class defines its methods as public, it describes how the class user interacts with the method.
Chapter 14 – Object Oriented Design. Copy Constructor u Called with an object as an argument u General declarator Class :: Class (Class& alias) –Class.
1 PHP and MySQL. 2 Topics  Querying Data with PHP  User-Driven Querying  Writing Data with PHP and MySQL PHP and MySQL.
Martin Kruliš This is an Object Oriented system. If we change something, the users object by Martin Kruliš (v1.0)1.
OOP with PHP Roman Bednarik
Object Oriented Programming in PHP. Topics Quick OOP Review Classes Magic Methods Static Methods Inheritance Exceptions Interfaces Operators Type Hinting.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 7 Structured Data and Classes.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
Introduction to c++ programming - object oriented programming concepts - Structured Vs OOP. Classes and objects - class definition - Objects - class scope.
Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 15 Inheritance.
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
21. PHP Classes To define a class, use the keyword class followed by the name and a block with the properties and method definitions Properties are declared.
PHP Reusing Code and Writing Functions 1. Function = a self-contained module of code that: Declares a calling interface – prototype! Performs some task.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Lesson 3 Functions. Lesson 3 Functions are declared with function. For example, to calculate the cube of a number function function name (parameters)
UNIT-IV WT. Why use classes and objects? PHP is a primarily procedural language small programs are easily written without adding any classes or objects.
Memory Management.
Introduction to Object-oriented Programming
Topic: Classes and Objects
Chapter 5: Enhancing Classes
Classes C++ representation of an object
By Muhammad Waris Zargar
CS 371 Web Application Programming
Friend Class Friend Class A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful.
Object Oriented PHP Martin Kruliš
Andy Wang Object Oriented Programming in C++ COP 3330
Arrays An array in PHP is an ordered map
Classes & Objects.
Class: Special Topics Copy Constructors Static members Friends this
More about OOP and ADTs Classes
Object Oriented PHP Martin Kruliš
Chapter 11 Developing Object-Oriented PHP PHP Programming with MySQL Revised by A. Philipp – Spring 2010 (Rev SP’11)
Templates.
This pointer, Dynamic memory allocation, Constructors and Destructor
Inheritance Basics Programming with Inheritance
CMSC 202 Interfaces.
Java Programming Language
More about OOP and ADTs Classes
Dynamic Scoping Lazy Evaluation
Constructors and Other Tools
More Object-Oriented Programming
Dr. Bhargavi Dept of CS CHRIST
Classes and Objects.
Computer Programming with JAVA
Classes, Constructors, etc., in C++
Object-Oriented Programming in PHP
Tonga Institute of Higher Education
CMSC 202 Interfaces.
Lecture 5: Functions and Parameters
CIS 199 Final Review.
Submitted By : Veenu Saini Lecturer (IT)
CS410 – Software Engineering Lecture #5: C++ Basics III
Classes C++ representation of an object
Object-Oriented PHP (1)
Classes and Objects Imran Rashid CTO at ManiWeber Technologies.
Class rational part2.
CMSC 202 Interfaces.
Creating and Using Classes
SPL – PS3 C++ Classes.
Presentation transcript:

Advance OOP in PHP

Overloading PHP Overloading can be broken down into two basic components Method overloading Property 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 __call ($name, $arguments) - when calling a method All overloading methods are invoked when accessing variable or method that is not declared or is inaccessible __set($index, $value) – when writing (property overloading) __get ($name) –when reading (property overloading) __call ($name, $arguments) - when calling a method

Overloading 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 Normally no property overloading

Example (Method Overloading) <?php class MyClass{  public function foo() {     return "This is the foo function";  } }  // create a new class object  $obj = new MyClass; $obj->bar(); ?> <?php class MyClass{  public function foo() {     return "This is the foo function";  }   /*** __call() method with two args ***/   public function __call($method, $arg){    echo $method.'<br />';    print_r($arg);  } }  $obj = new MyClass; /*** call a non-existant method ***/ $obj->bar("arg1", "arg2"); ?>

Example (Method Overloading) <?php class readyGetSet { private $item = 'Skate Board'; private $price = 100; function __call($method, $arguments){ /*** set property and prefix ***/ $prefix = strtolower(substr($method, 0, 3)); $property = strtolower(substr($method, 3)); if (empty($prefix) || empty($property)) { return; } if ($prefix == 'get' && isset($this->$property)) { return $this->$property; } if ($prefix == 'set') { $this->$property = $arguments[0]; } } } $obj = new readyGetSet; echo 'Item: ' . $obj->getItem() . '<br />'; echo 'Price: ' . $obj->getPrice() . '<br />'; $obj->setItem('CD'); $obj->setPrice(25); echo 'Item: ' . $obj->getItem() . '<br />'; echo 'Price: ' . $obj->getPrice() . '<br />';

Example (Property Overloading) <?php  class candy{  /*** declare a property ***/  public $type='chocolate';  /*** a normal method ***/  public function wrap(){    echo 'Its a wrap';  }  /*** our __set() function ***/  public function __set($index, $value){   echo 'The value of '.$index.' is '.$value;  } } /*** end of class ***/ /*** a new candy object ***/ $candy = new candy; /*** set a non existant property ***/ $candy->bar = 'Blue Smarties'; <?php  class candy{  public $type='chocolate';  public $choctype = array('milk'=>0, 'dark'=>1, 'plain'=>2);  public function wrap(){    echo 'Its a wrap';  }  public function __get($index){     echo 'Retrieving element of $choctype property with index of '.$index.'<br />';      return $this->choctype[$index];  } } /*** end of class ***/ /*** a new candy object ***/ $candy = new candy; /*** set a non existant property ***/  echo 'The value of the following element property is '.$candy->milk;

Object Iteration PHP provides a way for object to be iterated trough as a list of items (array) foreach can be used By default iterates all visible properties

Object Iteration – Example class A { public $var1 = 1; public $var2 = 2; protected $var3 = 3; private $var4 = 4; function printIteration () { foreach ($this as $key=>$val) echo "$key : $val\n"; } } $obj = new A(); // this prints only the public properties foreach ($obj as $key=>$val) echo "$key : $val \n"; // this prints protected and private too $obj->printIteration ();

Object Cloning $obj1 = new A(); $obj2 = clone $obj1; An object can be cloned with the clone keyword This will create new independent object Creating a copy of an object with fully replicated properties is not always the wanted behavior $obj1 = new A(); $obj2 = clone $obj1;

Object Cloning A class can implement the magic method __clone which is called for the newly created object Called "clone constructor" Allows necessary changes to be done on 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

Object Cloning Example class A { private $fileName; private $fp = null; public function open ($file) { $this->fileName = $file; $this->fp = fopen ($file, 'r'); } public function close () { if ($this->fp) { fclose($this->fp); $this->fp = null; } public function __clone () { // reopen the file for the new object if ($this->fp) $this->fp= fopen($this->file, 'r'); } }

Serializing Objects Serializing is the process of transforming an object into a string, that can be stored This string can be used to restore the object Useful for storing objects in session data Saves only properties values and class names – no methods PHP provides the serialize and unserialize functions

Serializing Objects serialize ($object) – returns string, representing the object unserialize ($string) – returns new object, that is restored from the serialized string unserialize requires the class to be defined before calling it

Serializing Object – Example class A { public $var; public function myPrint () { echo $this->var; } } $obj = new A; $obj->var = 10; $data = serialize ($obj); // store $data in a file file_put_contents ('data.dat', $data); // … // in a new page: $data = file_get_contents ('data.dat'); $obj = unserialize ($data); $obj->myPrint (); // prints 10

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 __wakeup allows the class to restore connections or other re-initialization

__sleep and __wakeup class Connection { protected $link; private $server, $user, $pass, $db; 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

__sleep and __wakeup // continues from previous slide public function __sleep () { // skip serializing $link return array ('server', 'user', 'pass', 'db'); } public function __wakeup () { $this->connect(); } }

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 In PHP all classes declarations are global Namespaces allow to have two classes with same name Old approach was adding prefixes to class names (Like the mysql_* functions) Available since PHP 5.3

Namespace Definition Namespaces are declared with the namespace keyword Should be always in the beginning of the file Namespace can contain classes, constants, functions but no free code <? namespace Project; class MyTemplate { … } function print_headers () { … } … ?>

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 The use operator allows aliasing namespaces names If new name is not specified the namespace is imported in the current context (global namespace) Even if aliased, every class and function can be accessed at any time by full name use Project::DB::MySQL as DBLink; $x = new DBLink::Connection(); DBLink::connect(); use Project::DB::MySQL; $x = new MySQL::Connection(); MySQL::connect();

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'; } ?> Exceptions, thrown in __autoload cannot be caught and result in fatal error

Limitation of self:: class A { public static function whoami () { Example: class A { public static function whoami () { echo __CLASS__; } public static function test () { self::whoami(); } } class B extends A { echo __CLASS__; } } B::test(); // outputs 'A' ?!

Late Static Binding PHP 5.3 introduces the late static binding which allows to reference the called class in context of static In practice – this adds static:: scope So if in the above example we use static::whoami() in the test() method body we get output 'B'