Object oriented programming in php 5

52
OBJECT ORIENTED PROGRAMMING IN PHP 5 Sayed Ahmed B.Sc. Engineering in Computer Science & Engineering M. Sc. in Computer Science Exploring Computing for 14+ years [email protected] http://sayed.justetc.net

Transcript of Object oriented programming in php 5

OBJECT ORIENTED PROGRAMMING IN PHP 5

Sayed Ahmed

B.Sc. Engineering in Computer Science & EngineeringM. Sc. in Computer ScienceExploring Computing for 14+ years

[email protected]://sayed.justetc.net

2

[email protected]

WHAT IS NEW IN PHP 5 FOR OOP The Object Model is rewritten

to allow for better performance and more features

PHP 5 treats objects as references or handles each variable contains an object reference rather than a

copy of the entire object See Objects and References

In PHP 5 When an object is sent

by argument, returned or assigned to another variable the different variables are not aliases: they hold a copy of the identifier (address variable or reference variable)

which points to the same object

10/9/2011

4

[email protected]

CLASS Example <?php

class SimpleClass{     // property declaration     public $var = 'a default value';

     // method declaration     public function displayVar() {         echo $this->var;     }

}

?>

10/9/2011

5

[email protected]

CLASS Class name can be any valid label which is a not

a PHP reserved word A valid class name

starts with a letter or underscore, followed by any number of

letters, numbers, or underscores Regular Expression for class name:

[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]* A class may contain

constants, variables (called "properties") and functions (called "methods")

The pseudo-variable $this is available To call other methods of the same class (within)

10/9/2011

6

[email protected]

CREATE OBJECTS, CREATE INSTANCES OF CLASSES new

the new keyword must be used to create an instance of a class

If the class is in a namespace its fully qualified name must be used

$instance = new SimpleClass(); A copy of an already created object

can be made by cloning it

10/9/2011

7

[email protected]

INHERITANCE : EXTENDS The keyword extends is used to

inherit the methods and properties of another class multiple classes inheritance is not allowed a class can only inherit from one base class

The inherited methods and properties can be overridden by re-declaring them

Final methods cannot be overridden [final] Overridden method signature has to be the same

Else E_STRICT error will be triggered Constructor can be overridden with different

parameters The overridden methods or static properties can

be accessed by referencing them with parent::.

10/9/2011

8

[email protected]

PROPERTIES Class member variables are called "properties“ Properties are declared with public, protected, or

private If declared using var (PHP 4 style), the property

will be defined as public However, PHP 5 will generate E_STRICT warning

public properties can be accessed everywhere protected properties can be accessed

only within the class itself and by inherited and parent classes

private properties may only be accessed by the class itself

The default visibility is public

10/9/2011

9

[email protected]

CLASSES/OBJECT FUNCTIONS Table of Contents call_user_method_array — Call a user method given with an array of

parameters [deprecated] call_user_method — Call a user method on an specific object [deprecated] class_alias — Creates an alias for a class class_exists — Checks if the class has been defined get_called_class — the "Late Static Binding" class name get_class_methods — Gets the class methods' names get_class_vars — Get the default properties of the class get_class — Returns the name of the class of an object get_declared_classes — Returns an array with the name of the defined classes get_declared_interfaces — Returns an array of all declared interfaces get_object_vars — Gets the properties of the given object get_parent_class — Retrieves the parent class name for object or class interface_exists — Checks if the interface has been defined is_a — Checks if the object is of this class or has this class as one of its parents is_subclass_of — Checks if the object has this class as one of its parents method_exists — Checks if the class method exists property_exists — Checks if the object or class has a property

10/9/2011

10

[email protected]

CLASS CONSTANTS Classes can have their own constants Interfaces can also have their own constants <?php

class MyClass{     const constant =  'constant value';

     function showConstant() {         echo  self::constant . "\n";     }

}

10/9/2011

11

[email protected]

CLASS CONSTANTS Example #2 Static data example <?php

class foo {     // As of PHP 5.3.0     const bar = <<<'EOT'

barEOT;

}

?>

10/9/2011

12

[email protected]

AUTOLOADING CLASSES You may define an __autoload function which is

automatically called in case you are trying to use a class/interface which hasn't been defined/included yet

spl_autoload_register() provides a more flexible alternative for autoloading classes

<?php

function __autoload($class_name) {     include $class_name . '.php';

}

$obj  = new MyClass1();$obj2 = new MyClass2(); 

?>

10/9/2011

13

[email protected]

SPL_AUTOLOAD_REGISTER EXAMPLE <?php

    class ClassAutoloader {        public function __construct() {            spl_autoload_register(array($this, 'loader'));        }        private function loader($className) {            echo 'Trying to load ', $className, ' via ', __METHOD__, "()\n";            include $className . '.php';        }    }

    $autoloader = new ClassAutoloader();

    $obj = new Class1();    $obj = new Class2();

?>

10/9/2011

14

[email protected]

CONSTRUCTOR PHP 5 constructor:

void __construct ([ mixed $args [, $... ]] ) Parent constructors are not called implicitly

if the child class defines a constructor parent::__construct() can be used in a

child to call parent constructor No E_STRICT error message when

__construct() is overridden with different parameters than the parent __construct()

if PHP 5 cannot find a __construct() function for a given class, it will search for the old-style constructor function,

10/9/2011

15

[email protected]

EXAMPLE #2 CONSTRUCTORS IN NAMESPACED CLASSES

<?phpnamespace Foo;class Bar {

     public function Bar() {// treated as constructor in PHP 5.3.0-5.3.2

         // treated as regular method as of PHP 5.3.3     }

}?>

10/9/2011

16

[email protected]

DESTRUCTOR void __destruct ( void )

The destructor method will be called as soon as there are no other references to a particular object, or in any order during the shutdown sequence

Like constructors parent destructors will not be called implicitly by the

engine In order to run a parent destructor

one would have to explicitly call parent::__destruct() in the child destructor body

The destructor will be called even if script execution is stopped using exit()

Exit can be called from destructors to stop execution Throwing exceptions from destructors will cause fatal

errors

10/9/2011

17

[email protected]

SCOPE RESOLUTION OPERATOR (::) is a token that allows access to

static constant and overridden

properties or methods of a class As of PHP 5.3.0, it's possible to reference the

class using a variable $classname = 'MyClass'; echo $classname::CONST_VALUE; // As of PHP 5.3

.0

10/9/2011

18

[email protected]

STATIC KEYWORD Declaring class properties or methods as

static makes them accessible without needing an instantiation of the class

A property declared as static can not be accessed with an instantiated class object (though a static method can)

the pseudo-variable $this is not available inside the method declared as static

Static properties cannot be accessed through the object using the arrow operator ->

Calling non-static methods statically generates an E_STRICT level warning

10/9/2011

19

[email protected]

ABSTRACT CLASSES Classes defined as abstract may not be

instantiated and any class that contains at least one

abstract method must also be abstract Methods defined as abstract simply declare

the method's signature - they cannot define the implementation

When inheriting from an abstract class all methods marked abstract in the parent's class

declaration must be defined by the child additionally, these methods must be defined with

the same (or a less restricted) visibility

10/9/2011

20

[email protected]

ABSTRACT CLASSES abstract class AbstractClass

{    // Force Extending class to define this method    abstract protected function getValue();    abstract protected function prefixValue($prefix);

    // Common method    public function printOut() {        print $this->getValue() . "\n";    }}

class ConcreteClass1 extends AbstractClass{    protected function getValue() {        return "ConcreteClass1";    }

    public function prefixValue($prefix) {        return "{$prefix}ConcreteClass1";    }}

10/9/2011

21

[email protected]

OBJECT INTERFACES Interfaces are defined

using the interface keyword in the same way as a standard class but without any of the methods having their contents

defined Object interfaces allow

to create code which specifies which methods a class must implement

without having to define how these methods are handled

All methods declared in an interface must be public, this is the nature of an interface

10/9/2011

22

[email protected]

IMPLEMENTING INTERFACES To implement an interface, the implements

operator is used Classes may implement more than one interface

if desired by separating each interface with a comma

A class cannot implement two interfaces that share function names, since it would cause ambiguity

Interfaces can be extended like classes using the extends operator

The class implementing the interface must use the exact same method signatures as are defined in the interface

10/9/2011

23

[email protected]

INTERFACE CONSTANTS interfaces can have constants Interface constants works exactly like

class constants except they cannot be overridden by a

class/interface that inherits it

10/9/2011

24

[email protected]

EXAMPLE: INTERFACES // Declare the interface 'iTemplate'

interface iTemplate{    public function setVariable($name, $var);    public function getHtml($template);}

// Implement the interface// This will workclass Template implements iTemplate{    private $vars = array();      public function setVariable($name, $var)    {        $this->vars[$name] = $var;    }      public function getHtml($template)    {        foreach($this->vars as $name => $value) {            $template = str_replace('{' . $name . '}', $value, $template);        }         return $template;    }}

10/9/2011

25

[email protected]

TRAITS Traits is a mechanism for code reuse in single inheritance

languages such as PHP enabling a developer to reuse sets of methods freely in several

independent classes living in different class hierarchies trait ezcReflectionReturnInfo {

    function getReturnType() { /*1*/ }    function getReturnDescription() { /*2*/ }}

class ezcReflectionMethod extends ReflectionMethod {    use ezcReflectionReturnInfo;    /* ... */}

class ezcReflectionFunction extends ReflectionFunction {    use ezcReflectionReturnInfo;    /* ... */}

10/9/2011

26

[email protected]

PRECEDENCE AND TRAITS An inherited member from a base class is

overridden by a member inserted by a Trait The precedence order is that members from

the current class override Trait methods which in return override inherited methods

Traits override base methods but current methods override traits

10/9/2011

27

[email protected]

OVERLOADING Overloading in PHP provides

means to dynamically "create" properties and methods

These dynamic entities are processed via magic methods

one can establish in a class for various action types The overloading methods are invoked

when interacting with properties or methods that have not been declared or are not visible in the current scope

All overloading methods must be defined as public None of the arguments of these magic methods

can be passed by reference

10/9/2011

28

[email protected]

METHOD OVERLOADING 5.3.0 Added __callStatic(). Added warning

to enforce public visibility and non-static declaration

5.1.0 Added __isset() and __unset()

10/9/2011

29

[email protected]

PROPERTY OVERLOADING void __set ( string $name , mixed $value ) mixed __get ( string $name ) bool __isset ( string $name ) void __unset ( string $name ) __set() is run when writing data to

inaccessible properties. __get() is utilized for reading data from

inaccessible properties. __isset() is triggered by calling isset() or

empty() on inaccessible properties. __unset() is invoked when unset() is used on

inaccessible properties.

10/9/2011

30

[email protected]

PROPERTY OVERLOADING Property overloading only works in object

context

10/9/2011

31

[email protected]

METHOD OVERLOADING Method overloading mixed __call ( string $name , array

$arguments ) mixed __callStatic ( string $name , array

$arguments ) __call() is triggered when invoking

inaccessible methods in an object context __callStatic() is triggered when invoking

inaccessible methods in a static context

10/9/2011

32

[email protected]

ACHIEVING JAVA LIKE OVERLOADING If you want to overload a function like in Java, don’t specify any arguments

and use the func_num_args and func_get_args function to get the number of arguments or the arguments themselves that were passed to that function:

function test() {    $args = function_get_args();    swtich (count($args)) {        case 1:            // one argument passed            break;        case 2:            // two arguments passed            break;        default:            // illegal numer of arguments            break;    }}

http://stackoverflow.com/questions/1512295/what-is-php-function-overloading-for

10/9/2011

34

[email protected]

OBJECT ITERATION PHP 5 provides a way for objects to be

defined so it is possible to iterate through a list of items

foreach statement. By default, all visible properties will be used for the iteration.

you can implement one of PHP 5's internal interface named Iterator. This allows the object to decide what and how the object will be iterated.

Interface methods to override: rewind(), current(), key() , next() , valid()

10/9/2011

37

[email protected]

PHP PATTERNS show a flexible solution to common programming problems. Factory

allows for the instantiation of objects at runtime class Example

{    // The parameterized factory method    public static function factory($type)    {        if (include_once 'Drivers/' . $type . '.php') {            $classname = 'Driver_' . $type;            return new $classname;        } else {            throw new Exception('Driver not found');        }    }}

// Load a MySQL Driver$mysql = Example::factory('MySQL');

// Load an SQLite Driver$sqlite = Example::factory('SQLite');

10/9/2011

38

[email protected]

PHP PATTERNS Singleton

The Singleton ensures that there can be only one instance of a Class and provides a global access point to that instance

often implemented in Database Classes Loggers Front Controllers or Request and Response objects

10/9/2011

39

[email protected]

SINGLETON EXAMPLE class Example

{    private static $instance;    private $count = 0;

    private function __construct()    {    }

    public static function singleton()    {        if (!isset(self::$instance)) {            echo 'Creating new instance.';            $className = __CLASS__;            self::$instance = new $className;        }        return self::$instance;    }

10/9/2011

40

[email protected]

USE OF SINGLETON $singleton = Example::singleton(); // prints "Crea

ting new instance."echo $singleton->increment(); // 0echo $singleton->increment(); // 1

$singleton = Example::singleton(); // reuses existing instance nowecho $singleton->increment(); // 2echo $singleton->increment(); // 3

// all of these will raise a Fatal Error$singleton2 = new Example;$singleton3 = clone $singleton;$singleton4 = unserialize(serialize($singleton));

10/9/2011

41

[email protected]

MAGIC METHODS __construct(), __destruct(), __call(), __callStatic(), __get(), __set(), __isset(), __unset(), __sleep(), __wakeup(), __toString(), __invoke(), __set_state() and __clone()

10/9/2011

43

[email protected]

FINAL KEYWORD Can be used before

A class name A method name

Properties cannot be declared final, only classes and methods may be declared as final.

prevents child classes from overriding a method by prefixing the definition with final

if the class itself is being defined final then it cannot be extended

10/9/2011

44

[email protected]

OBJECT CLONING To create a copy of an existing object

10/9/2011

45

[email protected]

COMPARING OBJECTS Using ==

Two object instances are equal if they have the same attributes and values, and are instances of the same class.

Using === object variables are identical if and only if they

refer to the same instance of the same class.

10/9/2011

46

[email protected]

TYPE HINTING Functions are now able to force parameters to be objects or arrays // An example class

class MyClass{    /**     * A test function     *     * First parameter must be an object of type OtherClass     */    public function test(OtherClass $otherclass) {        echo $otherclass->var;    }

    /**     * Another test function     *     * First parameter must be an array     */    public function test_array(array $input_array) {        print_r($input_array);    }}

10/9/2011

47

[email protected]

LATE STATIC BINDINGS To address the limitations of self:: Class A {

    public static function who() {        echo __CLASS__;    }    public static function test() {        static::who(); // Here comes Late Static Bindings (instead of self)    }}

class B extends A {    public static function who() {        echo __CLASS__;    }}

B::test();

10/9/2011

48

[email protected]

OBJECT SERIALIZATION serialize() returns a string containing a byte-

stream representation of any value that can be stored in PHP

spl_autoload_register() function

10/9/2011

50

[email protected]

OOP CHANGELOG http://ca.php.net/manual/en/language.oop5.changelog.php 5.4.0 Changed: If an abstract class defines a signature for the constructor it

will now be enforced. 5.3.3 Changed: Methods with the same name as the last element of a

namespaced class name will no longer be treated as constructor. This change doesn't affect non-namespaced classes.

5.3.0 Changed: Classes that implement interfaces with methods that have default values in the prototype are no longer required to match the interface's default value.

5.3.0 Changed: It's now possible to reference the class using a variable (e.g., echo $classname::constant;). The variable's value can not be a keyword (e.g., self, parent or static).

5.3.0 Changed: An E_WARNING level error is issued if the magic overloading methods are declared static. It also enforces the public visibility requirement.

5.3.0 Changed: Prior to 5.3.0, exceptions thrown in the __autoload function could not be caught in the catch block, and would result in a fatal error. Exceptions now thrown in the __autoload function can be caught in the catch block, with one proviso. If throwing a custom exception, then the custom exception class must be available. The __autoload function may be used recursively to autoload the custom exception class.

5.3.0 Added: The __callStatic method.

10/9/2011

51

[email protected]

OOP CHANGELOG 5.3.0 Added: heredoc and nowdoc support for class const and

property definitions. Note: heredoc values must follow the same rules as double-quoted strings, (e.g., no variables within).

5.3.0 Added: Late Static Bindings. 5.3.0 Added: The __invoke method. 5.2.0 Changed: The __toString method was only called when it

was directly combined with echo() or print(). But now, it is called in any string context (e.g. in printf() with %s modifier) but not in other types contexts (e.g. with %d modifier). Since PHP

5.2.0, converting objects without a __toString method to string emits a E_RECOVERABLE_ERROR level error.

5.1.3 Changed: In previous versions of PHP 5, the use of var was considered deprecated and would issue an E_STRICT level error. It's no longer deprecated, therefore does not emit the error.

5.1.0 Changed: The __set_state static method is now called for classes exported by var_export(). 5.1.0 Added: The __isset and __unset methods.

10/9/2011

52

[email protected]

REFERENCES http://

ca.php.net/manual/en/language.oop5.php

10/9/2011