PHP Oop
PHP Oop
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
• 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)
if (empty($prefix) || empty($property))
{
return;
}
if ($prefix == 'set')
{
$this->$property = $arguments[0];
}
}
}
class candy{
class candy{ public $type='chocolate';
/*** declare a property ***/ public $choctype = array('milk'=>0, 'dark'=
public $type='chocolate'; >1, 'plain'=>2);
$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
<?
namespace Project;
class MyTemplate { … }
function print_headers () { … }
…
?>
• Namespace can contain classes, constants, functions but
no free code
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
use Project::DB::MySQL as DBLink;
$x = new DBLink::Connection();
DBLink::connect();
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' ?!
LATE STATIC BINDING