Page 125 - Open Soource Technologies 304.indd
P. 125
Open Source Technologies
Notes 7.9.1 Creating an Object
Object Initialization: To create a new object, use the new statement to instantiate a class:
<?php
class foo
{
function do_foo()
{
echo “Doing foo.”;
}
}
$bar = new foo;
$bar->do_foo();
?>
Converting to object: If an object is converted to an object, it is not modified. If a value of any
other type is converted to an object, a new instance of the stdClass built-in class is created. If the
value was NULL, the new instance will be empty. Arrays convert to an object with properties
named by keys, and corresponding values. For any other value, a member variable named
scalar will contain the value.
<?php
$obj = (object) ‘ciao’;
echo $obj->scalar; // outputs ‘ciao’
?>
7.9.2 Object Inheritance
Inheritance is a well-established programming principle, and PHP makes use of this principle in
its object model. This principle will affect the way many classes and objects relate to one another.
For example, when you extend a class, the subclass inherits all of the public and protected
methods from the parent class. Unless a class overrides those methods, they will retain their
original functionality.
This is useful for defining and abstracting functionality, and permits the implementation of
additional functionality in similar objects without the need to remployment all of the shared
functionality.
Example: <?php
class foo
120 LOVELY PROFESSIONAL UNIVERSITY