1. Trang chủ
  2. » Công Nghệ Thông Tin

PHP 5 Power Programming P2

20 311 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề PHP 5 Power Programming P2
Trường học Standard University
Chuyên ngành Computer Science
Thể loại Bài luận
Năm xuất bản 2004
Thành phố City Name
Định dạng
Số trang 20
Dung lượng 273,66 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Allows the use of common OO access modifiers to control access to methods and properties: class MyClass { private $id = 18; public function getId { return $this->id; } } ☞ Unified cons

Trang 1

1.2 Language Features 3

The old object model not only led to the afore-mentioned problems, but also to fundamental problems that prevented implementing some additional features on top of the existing object model

In PHP 5, the infrastructure of the object model was rewritten to work with object handles Unless you explicitly clone an object by using the clone keyword, you never create behind-the-scenes duplicates of your objects In PHP 5, you don’t need a need to pass objects by reference or assign them by reference

sup-ported, in case you want to actually change a variable’s content (whether object or other type)

1.2.2 New Object-Oriented Features

The new OO features are too numerous to give a detailed description in this section Chapter 3, “PHP 5 OO Language,” details each feature

The following list provides the main new features:

☞ public/private/protected access modifiers for methods and properties Allows the use of common OO access modifiers to control access to methods and properties:

class MyClass { private $id = 18;

public function getId() { return $this->id;

} }

☞ Unified constructor name construct() Instead of the constructor being the name of the class, it is now declared

as construct(), which makes it easier to shift classes inside class hier-archies:

class MyClass { function construct() { print "Inside constructor";

} }

☞ Object destructor support by defining a destructor() method

Allows defining a destructor function that runs when an object

is destroyed:

class MyClass { function destruct() { print ”Destroying object”;

} Gutmans_Ch01 Page 3 Thursday, September 23, 2004 2:35 PM

Trang 2

4 What Is New in PHP 5? Chap 1

☞ Interfaces

Gives the ability for a class to fulfill more than one is-a relationships A class can inherit only from one class, but may implement as many interfaces as it wants: interface Display {

function display();

}

class Circle implements Display {

function display() {

print "Displaying circle\n";

}

}

☞ instanceof operator

Language-level support for is-a relationship checking The PHP 4 is_a() function

is now deprecated:

if ($obj instanceof Circle) {

print '$obj is a Circle';

}

The final keyword allows you to mark methods so that an inheriting class cannot overload them:

class MyClass {

final function getBaseClassName() {

return CLASS ;

}

}

☞ Final classes

After declaring a class as final, it cannot be inherited The following example would error out

final class FinalClass {

}

class BogusClass extends FinalClass {

}

☞ Explicit object cloning

To clone an object, you must use the clone keyword You may declare a clone() method, which will be called during the clone process (after the properties have been copied from the original object):

Gutmans_Ch01 Page 4 Thursday, September 23, 2004 2:35 PM

Trang 3

1.2 Language Features 5

class MyClass { function clone() { print "Object is being cloned";

} }

$obj = new MyClass();

$obj_copy = clone $obj;

Class definitions can now include constant values and are referenced using the class:

class MyClass { const SUCCESS = "Success";

const FAILURE = "Failure";

} print MyClass::SUCCESS;

You can now define methods as static by allowing them to be called from

because they are not bound to any specific object:

class MyClass { static function helloWorld() { print "Hello, world";

} } MyClass::helloWorld();

Class definitions can now include static members (properties) that are accessible via the class Common usage of static members is in the Singleton pattern:

class Singleton { static private $instance = NULL;

private function construct() { }

static public function getInstance() {

if (self::$instance == NULL) { self::$instance = new Singleton();

} return self::$instance;

} } Gutmans_Ch01 Page 5 Thursday, September 23, 2004 2:35 PM

Trang 4

6 What Is New in PHP 5? Chap 1

☞ Abstract classes

A class may be declared abstract to prevent it from being instantiated However, you may inherit from an abstract class:

abstract class MyBaseClass { function display() { print "Default display routine being called";

} }

A method may be declared abstract, thereby deferring its definition to an inheriting class A class that includes abstract methods must be declared abstract:

abstract class MyBaseClass { abstract function display();

}

☞ Class type hints

Function declarations may include class type hints for their parameters

If the functions are called with an incorrect class type, an error occurs: function expectsMyClass(MyClass $obj) {

}

☞ Support for dereferencing objects that are returned from methods

In PHP 4, you could not directly dereference objects that were returned from methods You had to first assign the object to a dummy variable and then dereference it

PHP 4:

$dummy = $obj->method();

$dummy->method2();

PHP 5:

$obj->method()->method2();

☞ Iterators

PHP 5 allows both PHP classes and PHP extension classes to implement

an Iterator interface After you implement this interface, you can iterate instances of the class by using the foreach() language

construct:

$obj = new MyIteratorImplementation();

foreach ($obj as $value) { print "$value";

Gutmans_Ch01 Page 6 Thursday, September 23, 2004 2:35 PM

Trang 5

1.2 Language Features 7

For a more complete example, see Chapter 4, “PHP 5 Advanced OOP and Design Patterns.”

☞ autoload().

Many developers writing object-oriented applications create one PHP source file per class definition One of the biggest annoyances is having to write a long list of needed inclusions at the beginning of each script (one for each class) In PHP 5, this is no longer necessary You may define an autoload() function that is automatically called in case you are trying to use

a class that has not been defined yet By calling this function, the scripting engine offers one last chance to load the class before PHP bails out with an error:

function autoload($class_name) { include_once($class_name "php");

}

$obj = new MyClass1();

$obj2 = new MyClass2();

1.2.3 Other New Language Features

exception-handling paradigm You are only allowed to throw objects that inherit from the Exception class:

class SQLException extends Exception { public $problem;

function construct($problem) { $this->problem = $problem;

} } try {

throw new SQLException("Couldn't connect to database");

} catch (SQLException $e) { print "Caught an SQLException with problem $obj->problem";

} catch (Exception $e) { print "Caught unrecognized exception";

}

Currently for backward-compatibility purposes, most internal functions

do not throw exceptions However, new extensions make use of this capability, and you can use it in your own source code Also, similar to the already exist-ing set_error_handler(), you may use set_exception_handler() to catch an unhandled exception before the script terminates

Gutmans_Ch01 Page 7 Thursday, September 23, 2004 2:35 PM

Trang 6

8 What Is New in PHP 5? Chap 1

☞ foreach with references

In PHP 4, you could not iterate through an array and modify its values PHP 5 supports this by enabling you to mark the foreach() loop with the

& (reference) sign, which makes any values you change affect the array over which you are iterating:

foreach ($array as &$value) {

if ($value === "NULL") { $value = NULL;

} }

☞ Default values for by-reference parameters

In PHP 4, default values could be given only to parameters, which are passed values PHP 5 now supports giving default values to by-reference parameters:

function my_func(&$arg = null) {

if ($arg === NULL) { print '$arg is empty';

} } my_func();

1.3.1 XML and Web Services

Following the changes in the language, the XML updates in PHP 5 are proba-bly the most significant and exciting The enhanced XML functionality in PHP

5 puts it on par with other web technologies in some areas and overtakes them

in others

variety of underlying XML libraries SAX support was implemented using the old Expat library, XSLT was implemented using the Sablotron library (or using libxml2 via the DOM extension), and DOM was implemented using the more powerful libxml2 library by the GNOME project

Using a variety of libraries did not make PHP 4 excel when it came to XML support Maintenance was poor, new XML standards were not always supported, performance was not as good as it could have been, and interopera-bility between the various XML extensions did not exist

In PHP 5, all XML extensions have been rewritten to use the superb libxml2 XML toolkit (http://www.xmlsoft.org/) It is a feature-rich, highly main-tained, and efficient implementation of the XML standards that brings cutting-edge XML technology to PHP

Trang 7

1.3 General PHP Changes 9

All the afore-mentioned extensions (SAX, DOM, and XSLT) now use libxml2, including the new additional extensions SimpleXML and SOAP

switched from using Expat to libxml2 Although the new extension should be compatible, some small subtle differences might exist Developers who still want to work with the Expat library can do so by configuring and building PHP accordingly (which is not recommended)

library, it had bugs, memory leaks, and in many cases, the API was not W3C-compliant The DOM extension went through a thorough facelift for PHP 5 Not only was the extension mostly rewritten, but now, it is also W3C-compliant For example, function names now use studlyCaps as described by the W3C standard, which makes it easier to read general W3C documentation and implement what you have learned right away in PHP In addition, the DOM extension now sup-ports three kinds of schemas for XML validation: DTD, XML schema, and RelaxNG

As a result of these changes, PHP 4 code using DOM will not always run

in PHP 5 However, in most cases, adjusting the function names to the new standard will probably do the trick

Sablotron extension and the XSLT support in the DOM extension PHP 5 fea-tures a new XSL extension and, as previously mentioned, it is based on the libxml2 extension As in PHP 5, the XSL Transformation does not take the XSLT stylesheet as a parameter, but depends on the DOM extension to load it The stylesheet can be cached in memory and may be applied to many docu-ments, which saves execution time

SimpleXML revolutionized the way PHP developers work with XML files Instead of having to deal with DOM or—even worse—SAX, SimpleXML repre-sents your XML file as a native PHP object You can read, write, or iterate over your XML file with ease, accessing elements and attributes

Consider the following XML file:

<clients>

<client>

<name>John Doe</name>

<account_number>87234838</account_number>

</client>

<client>

<name>Janet Smith</name>

<account_number>72384329</account_number>

Trang 8

10 What Is New in PHP 5? Chap 1

</client>

</clients>

The following code prints each client’s name and account number:

$clients = simplexml_load_file('clients.xml');

foreach ($clients->client as $client) { print "$client->name has account number $client

➥ >account_number\n";

}

It is obvious how simple SimpleXML really is

In case you need to implement an advanced technique in your Sim-pleXML object that is not supported in this lightweight extension, you can convert it to a DOM tree by calling it dom_import_simplexml(), manipulate it in DOM, and convert it to SimpleXML using simplexml_import_dom()

Thanks to both extensions using the same underlying XML library, switching between them is now a reality

com-monly used SOAP implementation was PEARs, but because it was imple-mented entirely in PHP, it could not perform as well as a built-in C extension Other available C extensions never reached stability and wide adoption and, therefore, were not included in the main PHP 5 distribution

SOAP support in PHP 5 was completely rewritten as a C extension and, although it was only completed at a very late stage in the beta process, it was incorporated into the default distribution because of its thorough implementa-tion of most of the SOAP standard

The following calls SomeFunction() defined in a WSDL file:

$client = new SoapClient("some.wsdl");

$client->SomeFunction($a, $b, $c);

(http://www.mysql.com) has written a new MySQL extension that enables you

to take full advantage of the new functionality in MySQL 4.1 and later As opposed to the old MySQL extension, the new one gives you both a functional and an OO interface so that you can choose what you prefer New features sup-ported by this extension include prepared statements and variable binding, SSL and compressed connections, transaction control, replication support, and more

first introduced in the PHP 4.3.x series It is an embedded SQL library that does not require an SQL server, so it is suitable for applications that do not require the scalability of SQL servers or, if you deploy at an ISP that does not

Trang 9

1.4 Other New Features in PHP 5 11

offer access to an SQL server Contrary to what its name implies, SQLite has many features and supports transactions, sub-selects, views, and large data-base files It is mentioned here as a PHP 5 feature because it was introduced

so late in the PHP 4 series, and because it takes advantage of PHP 5 by pro-viding an OO interface and supporting iterators

tidy.sf.net/) library It enables PHP developers to parse, diagnose, clean, and repair HTML documents The Tidy extension supports both a functional and

an OO interface, and its API uses the PHP 5 exception mechanism

the Perl extension allows you to call Perl scripts, use Perl objects, and use other Perl functionality natively from within PHP This new extension sits within the PECL (PHP Extension Community Library) repository at http:// pecl.php.net/package/perl

This section discusses new features introduced in PHP 5

1.4.1 New Memory Manager

The Zend Engine features a new memory manager The two main advantages are better support for multi-threaded environments (allocations do not need to perform any mutual exclusion locks), and after each request, freeing the allo-cated memory blocks is more efficient Because this is an underlying infra-structure change, you will not notice it directly as the end user

1.4.2 Dropped Support for Windows 95

Running PHP on the Windows 95 platform is not supported anymore due to Windows 95 does not support the functionality that PHP uses Because Microsoft officially stopped supporting it in 2002, the PHP development com-munity decided that dropping the support was a wise decision

You must surely be impressed by the amount of improvements in PHP 5 As previously mentioned, this chapter does not cover all the improvements, but only the main ones Other improvements include additional features, many bug fixes, and a much-improved infrastructure The following chapters cover PHP 5 and give you in-depth coverage of the named new features and others that were not mentioned in this chapter

Ngày đăng: 06/11/2013, 07:15

TÀI LIỆU CÙNG NGƯỜI DÙNG

TÀI LIỆU LIÊN QUAN