05 - OOP in PHP
05 - OOP in PHP
05 - OOP in PHP
[email protected]
trangntt
PHP 5
Content
Singleingle-inheritance
1. Creating an Object
2. Accessing attributes and methods
3. Building
Building a class
4. Introspection
Access
ccess--restricted
Overloadable
Object
~ passpass-byby-reference
1. Creating an Object
Content
1. Creating an Object
2. Accessing attributes and methods
3. Building
Building a class
4. Introspection
Syntax:
$object = new Class
Class([agrs])
([agrs]);
;
E.g.:
$obj1= new User();
User();
$obj2 = new User('Fred', "abc123"); //args
$obj3 = new User'; // does not work
$class = User';
User ; $obj4
$obj4= new $class; //ok
User
+ name
- password
- lastLogin
+ getLastLogin()
+ setPassword(pass)
Content
1. Creating an Object
2. Accessing attributes and methods
3. Building
Building a class
4. Introspection
E.g.
// attribute access
$obj1$obj1
->name = Micheal";
print("User name is " . $obj1$obj1->name);
$obj1$obj1
->getLastLogin( ); // method call
// method call with args
$obj1$obj1
->setPassword("Test4");
Must include:
ASCII letter
(a--zA
(a
zA--Z)
Digits (0(0-9)
_
ASCII character
between 0x7F
(DEL) and
0xFF
Do not start
by a digit
10
User
Constructor
__construct([agrs])
construct([agrs])
executed immediately upon creating an object
from that class
Destructor
__destruct()
destroying
ying the object
calls when destro
2 special namespaces:
selft: refers to the current class
parent: refers to the immediate ancestor
Call parents constructor: parent::__construct
12
class BaseClass{
protected $name = "BaseClass";
function __construct(){
print("In " . $this
$this->name . " constructor<br>");
}
function __destruct(){
print("Destroying
p
(
y g " . $
$this->name . "<br>");
$this);
}
}
class SubClass extends BaseClass {
function __construct(){
$this$this
->name = "SubClass";
parent::__construct();
}
function __destruct(){
parent::__destruct();
}
}
Example
Static member
Not relate
relate/belong
/belong to an any particular object of the
class, but to the class itself.
itself.
Cannot use $this to access static members but can use
with self namespace or ClassName.
E.g.
count
self::$count
Constant member
value cannot be changed
can be accessed directly through the class or within
object methods using the self namespace.
13
class Counter {
private static $count = 0;
const VERSION = 2.0;
function __construct(){ self::$count++; }
function __destruct(){ self::$count-self::$count--;
; }
static function getCount() {
return self::$count;
}
}
$c1 = new Counter();
print($c1print($c1
->getCount() . "<br>
"<br>\
\n");
$c2 = new Counter();
print(Counter::getCount() . "<br>\
"<br>\n");
14
Example
$c2 = NULL;
print($c1print($c1
->getCount() . "<br>
"<br>\
\n");
print("Version used: ".Counter::VERSION."<br>\
".Counter::VERSION."<br>\n");
15
16
Example Cloning
class ObjectTracker {
private static $nextSerial = 0;
private $id, $name;
function __construct($name) {
$this$this
->name = $name;
thisthis
->id = ++self::$nextSerial;
}
function __clone(){
$this$this
->name = "Clone of $th
$this
is->name";
$this$this
->id = ++self::$nextSerial;
}
function getId() { return($thisreturn($this->id); }
function getName() { return($thisreturn($this->name); }
function setName($name) { $this$this->name = $name; }
}
$ot = new ObjectTracker("Zeev's Object");
$ot2 = clone $ot; $ot2$ot2->setName("Another object");
print($otprint($ot
->getId() . " " . $ot
$ot->getName() . "<br>");
print($ot2print($ot2
->getId() . " " . $ot2
$ot2->getName() . "<br>");
Call cloning:
$copy_of_object = clone $object;
E.g.
E
$a = new SomeClass();
$b = clone $a;
17
18
void __unset
unset (string $name)
is invoked when unset() is used on inaccessible
attributes
19
Note: The return value of __set() is ignored because of the way PHP
processes the assignment operator. Similarly, __get() is never
called when chaining assignments together like this:
$a = $obj$obj->b = 8;
20
class PropertyTest {
private $data = array();
Example - Attribute overloading
public $declared = 1;
private $hidden = 2;
public function __set($name, $value) {
echo "Setting '$name' to '$value'<br>";
thisthis
->data[$name] = $value;
}
public function __get($name)
get($name) {
echo "Getting '$name'<br>";
if (array_key_exists($name, $this$this->data)) {
return $this$this->data[$name];
}
$obj = new PropertyTest;
}
public function __isset($name) {
$obj$obj
->a = 1;
echo "Is '$name' set?<br>";
$obj->a."<br>";
return isset($thisisset($this->data[$name]); echo $obj}
var_dump(isset($objvar_dump(isset($obj
->a));
public function __unset($name) {
unset($objunset($obj
->a);
echo "Unsetting '$name'<br>";
var_dump(isset($objvar_dump(isset($obj
->a));
unset($thisunset($this
->data[$name]);
echo "<br>";
}
public function getHidden() {
echo $obj$obj->declared."<br>";
return $this$this->hidden;
echo $obj$obj->getHidden()."<br>";
}
echo $obj$obj->hidden."<br>";
}
22
Example
Method Overloading
class MethodTest {
public function __call($name, $arguments) {
// Note: value of $name is case sensitive.
echo "Calling object method '$name' "
. implode(', ', $arguments). <br>";
}
23
24
3.7. Namespace
~folder, ~package
Organize
O
i variables,
i bl
ffunctions
ti
and
d classes
l
Avoid confliction in naming variables,
functions and classes
The namespace statement gives a name
to a block of code
From outside the block, scripts must refer
to the parts inside with the name of the
namespace using the :: operator
25
26
Example Namespace
27
namespace core_php:utility {
class TextEngine {
public function uppercase($text) {
return(strtoupper($text));
}
import * from myNamespace
}
function uppercase($text) {
$e = new TextEngine;
return($ereturn($e
->uppercase($text));
}
}
$e = new core_php:utility::textEngine;
print($eprint($e
->uppercase("from object") . "<br>");
print(core_php:utility::uppercase("from function")
."<br>");
import class TextEngine from core_php:utility;
$e2 = new textEngine;
28
Single
inheritance
Abstract methods, abstract classes,
interface (implements) like Java
You cannot instantiate an
an abstract
class,, but you can extend it or use it
class
in an instanceof expression
29
30
$myCollection = array();
31
foreach($myCollection as $s) {
if($s instanceof Shape) {
print("Area: " . $s$s->getArea() . "<br>
"<br>\
\n");
}
if($s
($ instanceof Polygon)
yg ) {
print("Sides: " . $s$s->getNumberOfSides() . "<br>
"<br>\
\n");
}
if($s instanceof Color) {
print("Color: $s$s->name<br>
>name<br>\
\n");
}
print("<br>\
print("<br>
\n");
32
}
Content
4. Introspection
1. Creating an Object
2. Accessing attributes and methods
3. Building
Building a class
4. Introspection
33
class_exists(c
class_exists(
class
lassn
name)
determine whether a class exists
get_declared_cl
get_declared_c
lasses()
get_class_methods(classname
get_class_methods(
classname)
)
get_class_vars
_
_
(classname)
(classname
)
get_parent_class(classname
get_parent_class(
classname)
)
34
function display_classes ( ) {
$classes = get_declared_classes( );
foreach($classes as $class) {
echo "Showing information about $class<br />";
echo "$class methods:<br />";
$methods = get_class_methods($class);
if(!count($methods)) {
echo "<i>None</i><br
<i>None</i><br />";
/> ;
} else { foreach($methods as $method) {
echo "<b>$method</b>( )<br />";
}
}
echo "$class attributes:<br />";
$attributes = get_class_vars($class);
if(!count($attributes)) { echo "<i>None</i><br />; }
else {
foreach(array_keys($attributes) as $attribute) {
echo "<b>\
"<b>\$$attribute</b><br />";
}
}
echo "<b
"<br />";
}
}
36
is_object(object
is_object(
object)
)
get_class(object)
method_exists(object,
method_exists(
object, method
method)
)
get_object
get_
_object_vars(
_vars( object
_
object)
)
get_parent_class(object
get_parent_class(
object)
)
Question?
38
10