Вы находитесь на странице: 1из 8

PHP OOP

Objects hide a lot of their inner workings away from the code that uses them,
providing instead easy interfaces through which you can send them orders and they
can return information. These interfaces are special functions called methods. All
the methods of an object have access to special variables called properties.

To create an object, you must first design the template from which it can be
instantiated. This template is known as a class, and in PHP, you must declare it
with the class keyword:

class Item {
// a very minimal class
}
$obj1 = new Item();
$obj2 = new Item();
print "\$obj1 is an ".gettype($obj1)."<br />";
print "\$obj2 is an ".gettype($obj2)."<br />";

Object Properties
Objects have access to special variables called properties. You can declare them
anywhere within the body of your class. A property can be a value, an array, or
even another object:

class Item {
var $name = "item";
}

$obj1 = new Item();


$obj2 = new Item();
$obj1->name = "widget 5442";
print "$obj1->name<br />";
print "$obj2->name<br />";
The -> operator allows you to access or change the properties of an object.

Object Methods
A method is a function defined within a class. Every object instantiated from the
class has the method's functionality.

class Item {
var $name = "item";

function getName() {
return "item";
}
}

$item = new Item ();


print $item->getName ();
// outputs "item
Accessing a Property from Within a Method
<?php
class Item {
var $name = "item";

function getName () {
return $this->name;
}
}
$item = new Item ();
$item->name = "widget 5442";
print $item->getName ();
// outputs "widget 5442"
?>
A class uses the special variable $this to refer to the currently instantiated
object

Although you refer to an object by the handle you have assigned it to ($item, for
example), an object must refer to itself by means of the $this variable. Combining
the $this pseudovariable and ->, you can access any property or method in a class
from within the class itself.

Changing the Value of a Property from Within a Method


<?php
class Item {
var $name = "item";

function setName( $n ) {
$this->name = $n;
}

function getName() {
return $this->name;
}
}

$item = new Item();


$item->setName("widget 5442");
print $item->getName ();
Object Constructors
if we expect the $name property to hold a different value for every instance of the
Item class, we would do better to offer the client coder the chance to set the
$name property when the object is initialized. We can use a special function called
a constructor to set properties and perform any other preparatory work we require.
A constructor is automatically called when the object is instantiated using the new
keyword.

class Item {

var $name;

function Item( $name="item") {

$this->name = $name; }

function setName( $n) {

$this->name = $n; }

function getName () {

return $this->name;

}
}

$item = new Item("widget 5442");

print $item->getName ();

PHP 5 introduces a new syntax for constructor methods. Instead of using the name of
the class, you can use the special syntax __construct().

Limiting Access to Object Properties

class item {
var $name;
var $code;
var $productString;

function Item( $name="item", $code=0 ) {


$this->name = $name;
$this->code = $code;
$this->setName( $name );
}

function getProductString () {
return $this->productString;
}

function setName( $n ) {
$this->name = $n;
$this->productString = $this->name." ".$this->code;
}

function getName () {
return $this->name;
}
}

$item = new Item ("widget", 5442);


print $item->getProductString ();
// outputs "widget 5442"

print "<br />";

$item->name = "widget-upgrade";
print $item->getProductString ();

PHP 5 Property Declaration Keywords

Privacy Level

Description

public

Accessible to all. Equivalent to var.

private

Available only to the containing class.


protected

Available only to the containing class and subclasses.

private $name;
private $code;
private $productString;

Client coders are now forced to use the setName() method to change the $name
property.

Limiting Access to Object Methods


A principle of object-oriented code is that you should only expose as much of a
class as you absolutely have to. Objects should have clearly defined
responsibilities and clear public interfaces.

function setName( $n ) {
$this->name = $n;
$this->makeProductString( $n, $this->code );
}
function makeProductString( $string, $code) {
return $this->productString = "$string $code";
}

The makeProductString() function is now accessible only by methods in the Item


class. You can apply three possible privacy keywords to method declarations. public
is the default and is implicit. A method declared with the public keyword (or with
no privacy keyword at all) is accessible from any context. Methods declared private
are accessible only to other methods in the enclosing class.

Inheritance
To create a class that inherits functionality from a parent class, we need to alter
our class declaration slightly.

class Item {
var $name;

function Item( $name="item", $code=0) {


$this->name = $name;
$this->code = $code;
}

function getName() {
return $this->name;
}
}

class PriceItem extends Item {

$item = new PriceItem( "widget", 5442 );


print $item->getName ();
Overriding the Method of a Parent Class
class Item {
var $name;

function Item( $name="item", $code=0) {


$this->name = $name;
$this->code = $code;
}

function getName() {
return $this->name;
}
}

class PriceItem extends Item {


function getName() {
return "(price)."$this->name;
}
}

$item = new PriceItem( "widget", 5442 );


print $item->getName();
class Item { private $name; // ...
The PriceItem class does not have access to the $name property. If your child
classes need to access methods or properties of their ancestor classes, then you
should use the protected keyword inpreference to private.

Calling an Overridden Method


Occasionally, you want the functionality of a parent class's method as well as the
benefit of your own additions. You can refer to a parent class using the parent
keyword.

class Item {
private $name;

function __construct( $name="item", $code=0 ) {


$this->name = $name;
$this->code = $code;
}

function getName() {
return $this->name;
}
}

class PriceItem extends Item {


function getName() {
return "(price) ".parent::getName ();
}
}

$item = new PriceItem ("widget", 5442);


print $item->getName();

Working with Constructors


We have seen that a parent class's constructor is automatically called if the child
class does not define its own constructor method. If the child class does define a
constructor, it becomes responsible for calling the constructor of its parent.

Adding a Constructor to PriceItem


<?php
class Item {
private $name;

function __construct( $name="item", $code=0 ) {


$this->name = $name;
$this->code = $code;
}

function getName () {
return $this->name;
}
}

class PriceItem extends Item {


private $price;

function __construct( $name, $code, $price ) {


parent::__construct( $name, $code );
$this->price = $price;
}

function getName() {
return "(price) ".parent::getName ();
}
}

$item = new PriceItem ("widget", 5442, 5.20);


print $item->getName ();

Testing Classes and Objects


You can query the type of any object with the get_class() function.get_class()
accepts an object and returns the name of its class (in lowercase letters). So
given an array of objects, you might want to test each one before working with it:

foreach ( $objectArray as $obj ) {


if ( get_class( $obj ) == "priceitem" ) {
print "doing a pricey thing\n";
} else {
die ("not designed to handle ".get_class( $obj ) );
}
}

Checking for Class and Method Existence


class_exists() requires a string representing a class name. If the user-defined
class is found, the function returns true. Otherwise, it returns false.
class_exists() is especially useful when using class names stored in strings:

if ( class_exists( $class_name ) ) {
$obj = new $class_name( );
}
method_exists() requires two arguments, an object and a string containing the name
of the method you are checking for:

if ( method_exists( $filter_object, "filter") ) {


print $filter_object->filter( "hello you<br />" );
Storing and Retrieving Objects
Usually, you separate your objects from data storage. In other words, you use saved
data to construct objects, and then when you are done, you store the data again.
Occasionally, however, you want your object and data to persist intact. PHP
provides two functions to help you.

To "freeze-dry" an object, you should pass it to the serialize() function.


serialize() produces a string that you can then store in a file or a database or
transmit to another script:

class apple {
var $flavor="sweet";
}
$app = new apple();
$stored = serialize( $app );
print $stored;

You can convert the string produced by serialize() back into an object with the
unserialize() function. If the original class is present at the time unserialize()
is called, an exact copy of the original object is produced:

$new_app = unserialize( $stored );


print $new_app->flavor;

In some circumstances, you need your objects to clean up a little before storage.
This cleanup is particularly important if an object has a database connection open
or is working with a file. By the same token, you might want your object to perform
some sort of initialization when it is woken up. You can handle these needs by
including two special methods in any object that might need to be serialized.

The __sleep() method is automatically called by serialize() before it packs up the


object. This process allows you to perform any cleanup operations you might need.
For the serialization to work, your __sleep() method must return an array of the
property names that you want to be saved in the serialized string:

class apple {
var $flavor="sweet";
var $frozen = 0;
function ___sleep( ) {
$this->frozen++;
// any clean up stuff goes here
return array_keys( get_object_vars( $this) );
}
}
$app = new apple ( );
$stored = serialize( $app );
print $stored;

PHP also supports a special method called __wakeup(). If it is defined, it is


automatically called by unserialize(). This process enables you to resume database
connections or to provide any other initialization the object might need. We might
add the following method to our apple class:

function __wakeup( ) {
print "This apple has been frozen ".$this->frozen." time(s)";
// any initialization stuff goes here
}
Now that we have added __wakeup(), we can call unserialize();
$new_app = unserialize( $stored );
// prints "This apple has been frozen 1 time(s)"

Вам также может понравиться