PHP5 for object-oriented

Source: Internet
Author: User
Tags final functions getmessage new features variables version variable zend
Php5| Object Abstract] in the current development of the PHP5, its object-oriented function has been greatly enhanced. What kind of language will the next generation of PHP be? Here's a detailed explanation of the current beta release of PHP5.




(i) The birth of Zend 2.0
The basic grammar used by today's PHP4 is a script-compilation engine called the Zend Engine. This is one of the reasons for the excellent functioning of PHP4, a language produced as an improvement to the PHP3. Everyone has always believed that the performance of PHP4 according to the original goal, than PHP3 has a great promotion, in the world of network programming occupies a large share.

The Zend company that developed the Zend engine was merged with the PHP4 created by PHP3 's main developer Zeev Suraski and Andi. The name of the Zend is composed of the names of Zeev and Andi. Zend's business model is to continuously provide the PHP kernel (core) of the Zend Engine for open source, while promoting the benefits of product development and trafficking around the edges. Business, with open source software as a base, is a good example in most struggling companies around the world.

Limitations of the PHP4

Thanks to PHP4 's success, the scope of this application has become wider. Using PHP as an enterprise-class use is something to hear. Therefore, there is such a problem, the construction of large-scale web sites, the reuse of code is very poor. Specifically, PHP4 's object-oriented performance is weak, so technicians accustomed to using Java have a lot of complaints about it.

By gradually improving the object-oriented performance of PHP4, and greatly changing the basic grammar, the developer has achieved the pioneering purpose of updating the PHP description method.

Zend 2.0 began to develop
Subsequently, developers of Zend's PHP Center published their vision for the Zend 2.0 engine as the next-generation PHP language engine in July 2001. With [Zend Engine version 2.0:feature Overview and design]
(http://www.zend.com/engine2/ZendEngine-2.0.pdf) as a target, the object-oriented performance is greatly enhanced.
The current expansion of the PHP4 Zend engine is the same as that of former PHP3. This means raising the major version number of the new language engine, clarifying the methodological objectives, and meeting the praise from the development community.

Ze2 's development, like the previous Zend engine, is run in open source mode. The latest source code is fully publicized on CVS because it is open to developers and the discussion about development is very active.

Ze2 is now determined to be used in the next version of PHP PHP5. The time for the final release is still undecided, but if the Zend company released April 1, 2003 newsletter, it should be beta release.


(ii) New characteristics of PHP5

Next, look at the performance of the enhanced PHP5 in order. The first is the most important object-oriented performance, the physical characteristics of the class are significantly modified. This is only about the new attributes of the class.

· The reference transition for an object is default
· Restrictions on introducing access properties
· Restrictions on introducing access methods
· Abstract classes and abstract methods
· Interface
· Final statement
· Name space
· Constants in class
· class variables
· Unified Builder
· destructor (Distructor)
· Other ancillary features

The above content is based on the April 22, 2003 CVS on the version of the data written, before the formal release, there are changes in the possibility.

Default reference transitions for objects

In PHP4, if the $VAR2 = $var 1 When a variable is $var1 as an entity object of the class, then in $var2, the replication of $var 1 is replaced. Obviously, $var 2 to point to the same object as $VAR1, it is written as $var2 =& $var 1, and must be added with & as a reference.
In PHP5, the generation of objects becomes an automatic reference transition. Other words
$var 2= $var 1, both point to the same object. If you want to take copy with PHP4, you will use the method of importing __clone ().
$var 2 = $var 1->__clone (); Here, the clone is preceded by two consecutive "_"
(This is just the attribute of the entity of the Class)


Restrictions on introducing access properties

In PHP4 classes, along with the properties and methods, you can freely access any place within and outside the class without restrictions. As a result, users cannot prevent inadvertent changes to properties.

In PHP5, like C + + and Java, the access restrictions of private, protected, public three levels are imported, allowing the designer of the class to qualify the methods used for the properties and methods. The following are the meanings of the various access restrictions.

· Public: Be free to refer to and change anywhere within and outside the class
· Private: Reference, change only in the method of this class
· Protected: The ability to reference and change in this class and in the methods of another class that inherits the class. In addition, in an inherited class, you can write access designations.

The "Var" in PHP4, as usual, has the same meaning as public. Here's an example, let's see how the Access restrictions work.

PHP Code:--------------------------------------------------------------------------------
Class Hoge1 {
Private $var 1 = ' A ';
Protected $var 2 = ' B ';
Protected $var 3 = ' C ';

function Setlower () {
$this->var1 = ' a ';
$this->var2 = ' B ';
$this->var3 = ' C ';
}
function var1 () {
return $this->var1;
}
function Var2 () {
return $this->var2;
}
function Var3 () {
return $this->var3;
}
}

--------------------------------------------------------------------------------

In this class, with $var1, $var 2, $var 33 properties. $var 1 is declared private, $var 2 and $VAR3 are protected. Here

PHP Code:--------------------------------------------------------------------------------
$hoge =new Hoge1;
Echo ' var1: '. $hoge->var1. "
N

--------------------------------------------------------------------------------

If you try to reference a private property that is not allowed to be accessed externally, the following error occurs:

Fatal error:cannot Access Private hoge1:: $var 1 in/path/to/script.php on line XX

The same is true for protected $var2.

However, because the $hoge method is not private and protected, the following code works correctly, returning the value of the internal private and protection variables.

PHP Code:--------------------------------------------------------------------------------
Echo ' var1: '. $hoge->var1 (). "
\ n "; Var1:a
Echo ' var2: '. $hoge->var2 (). "
\ n "; Var2:b
Echo ' Var3: '. $hoge->var3 (). "
\ n "; Var3:c

$hoge->setlower ();

Echo ' var1: '. $hoge->var1 (). "
\ n "; Var1:a
Echo ' var2: '. $hoge->var2 (). "
\ n "; Var2:b
Echo ' Var3: '. $hoge->var3 (). "
\ n "; Var3:c

--------------------------------------------------------------------------------

Second, in order to be able to see the state of protected's attributes, we tried to create classes that inherited Hoge1 Hoge2

PHP Code:--------------------------------------------------------------------------------
Class Hoge2 extends Hoge1 {
Public $var 3 = ' 3 ';

function D_var1 () {
return $this->var1;
}
function D_var2 () {
return $this->var2;
}
function D_var3 () {
return $this->var3;
}
}

--------------------------------------------------------------------------------

In class Hoge2, only $VAR3 is declared public. In the case where the attribute is protected, the restriction on access from the subclass is determined by the attribute declaration of the subclass. In Hoge2, because $VAR3 is declared public, it is possible to access Hoge2 $VAR3 from anywhere (the entity is Hoge1 $VAR3). Because $var1 is private in Hoge1, $var1 in the Hoge2 subclass is not inherited, and a property named Hoge2 is likely to be made in $var1, so it is important to distinguish Hoge1:: $var 1 and hoge2::$ Var1.

PHP Code:--------------------------------------------------------------------------------
$hoge = new Hoge2;

Echo ' var1: '. $hoge->var1. "
\ n "; VAR1:
Echo ' var2: '. $hoge->var2. "
\ n "; Error
Echo ' Var3: '. $hoge->var3. "
\ n "; Var3:3

Echo ' var1: '. $hoge->d_var1 (). "
\ n "; VAR1:
Echo ' var2: '. $hoge->d_var2 (). "
\ n "; Var2:b
Echo ' Var3: '. $hoge->d_var3 (). "
\ n "; Var3:3

--------------------------------------------------------------------------------


$hoge->VAR1 is a variable that has nothing to do with hoge1::var1, so there is no display because VAR2 has protected access restrictions, so a fatal error can occur if you refer directly to $var2 without using method.

Restrictions on introducing access methods

Same as above, here is also divided into private, protected, public three kinds.

· Public: Able to invoke from anywhere
· Private: Can only be invoked from within the method of this class
· Protected: Can only be invoked from this class and from the subclass method

The meaning here is the same as Java and C + +, please do not confuse.

Abstraction (abstract) classes and abstract methods

Supports the same abstract classes and abstract methods as java. Abstract methods provide only the way the method name is invoked, without providing an entity. In addition, classes that hold abstract methods must abstract the declaration class itself. If you want to make an object directly into an abstract class, the following fatal error occurs.

Fatal Error:cannot Instantiate abstract class ClassName

The actual example of the error is as follows:

PHP Code:--------------------------------------------------------------------------------



Abstract class Myabstract {
Abstract public Function test ();
Public Function test2 () {
echo "Myabstract::test2 () called.
\ n ";
}
}

Class Myimplement extends Myabstract {
Public Function test () {
echo "Myimplement::test () called.
\ n ";
}
}

$obj = new Myimplement;
$obj->test ();

?>

--------------------------------------------------------------------------------


Interface (interface)

Supports the same interface as Java (interface). Interfaces are designed to fit the described external invocation form.
The entity of the interface cannot be logged. Instead, the class that implements the interface must hold the entity corresponding to the square method of the interface. In addition, a class can implement multiple interfaces, so it is possible to implement multiple inheritance.

PHP Code:--------------------------------------------------------------------------------


Interface Throwable {
Public function getMessage ();
}

Interface Serializable {
Public function toString ();
}

Class MyException implements Throwable, Serializable {
Public Function GetMessage () {
Return ' This is myexception message ';
}

Public Function toString () {
Return ' myexception:this are myexception message ';
}
}

$e = new MyException;
echo $e->getmessage ();
echo $e->tostring ();
?>

--------------------------------------------------------------------------------


Final statement

Like Java, PHP5 supports final statements. If the final declaration is appended to a method, this method will certainly not overload the subclass (Override). If the method is declared by final, but is also overloaded in subclasses, the following error occurs:

PHP Code:--------------------------------------------------------------------------------
Fatal Error:cannot Override final Method Fuga::foo ()

--------------------------------------------------------------------------------


Examples of errors that occur:

PHP Code:--------------------------------------------------------------------------------

Class Fuga {
Final function foo () {
echo "This is final function\n";
}
}

Class Hoge extends Fuga {
function foo () {
echo "This isn't final function\n";
}
}
?>

--------------------------------------------------------------------------------


(iii) new features of PHP5 (continued)

PHP5 's release plan

As we mentioned in the previous article, "according to the Zend Company's April 1, 2003 message, it should be beta release now", but the result of the discussion within the developer is that beta is premature and may not be beta releases.

Interested in this direction can refer to the information published on the news://news.php.net/php.version5.dev:372

In this document, PHP5 's release plan is back to a piece of white paper, and on the other hand, the development of Zend Engine2 is underway. PHP5 's release is basically looking forward to "the end of the year."

New characteristics of PHP5

Then let's take a look at some of the other new functions of the class mentioned earlier

Name space

PHP5 Support name space. Therefore, we can load classes, variables, constants, and functions in the name space.

In the scope of PHP4, there are only three categories in global, function, and class, so it is very easy to "pollute" global space if you don't pay attention. If we use the name space, we can separate the variable namespace in the package, so we should be able to make the independent package easily.

Use the following example:

PHP Code:--------------------------------------------------------------------------------
Namespace this {
Class Hoge {
}
Const Aconstant = ' This Constant ';
function Afunction () {}
var $aVariable = ' This Variable ';
}

$obj = new This::hoge;
Echo This::aconstant. "
\ n ";
This::afunction ();
echo this:: $aVariable. "
\ n ";

--------------------------------------------------------------------------------


Suppose you want to access objects within a namespace, you should do this:

Name Space Name:: Object Name

But PHP5 's name space will not be nested in the same way as C + +.

Class Inner constants

Using the keyword const, you can define constants within a class, a name space. This is because it is a constant, so be sure to precede the constant name with $. The constants within class are higher than the global constants in this class.

Here the const is the reservation language, so you need to make the necessary corrections when using the const in the class name and function name.

PHP Code:--------------------------------------------------------------------------------


Define (' Constant_value ', ' global constant ');

Class MyClass {
Const CONSTANT_VALUE = ' class constant ';

function Printconstant () {
Print Constant_value;
}
}

Echo Myclass::constant_value. "
\ n ";
Myclass:rintconstant ();
?>

--------------------------------------------------------------------------------


In this example, Myclass:rintconstant () is the value that displays the constant Constant_value, but constant_value exists in the global space and in the two places within the class. In this case, the constant constant_value within the MyClass is higher in priority and is displayed as "class constant".

Object variables

Even if the class is not instantiated, the object variable can be initialized exactly with the specified value. The methods of access are as follows:

Class Name:: $ variable Name

PHP Code:--------------------------------------------------------------------------------


Class Hoge {
static $my _static = 5;
}

Print Hoge:: $my _static;
?>

--------------------------------------------------------------------------------


Unified Builder

The method that can be invoked automatically when an object is generated is called a "builder."

The builder in PHP4 is the same method name as the class name. This is the same place as Java and C + +, so for some people who are used to it, there is no sense of awkwardness. However, if you want to invoke the parent class builder from a subclass, you must specifically write the name of the parent class in PHP.

In PHP, the parent class Builder cannot be invoked automatically, so the situation is much more.
In PHP5, the __constructor name of the builder is adopted uniformly, regardless of the class name, which is called __construct () and is treated as a builder.

In addition, given the interchangeability of the same PHP4, if it exists in the previous builder name with the same class name, use that builder preferentially.

PHP Code:--------------------------------------------------------------------------------


Class BaseClass {
function __construct () {
Print "in BaseClass constructor\n";
}
}

Class Subclass extends BaseClass {
function __construct () {
Parent::__construct ();
Print "in subclass constructor\n";
}
}

$obj = new BaseClass ();
$obj = new Subclass ();
?>

--------------------------------------------------------------------------------


destructor

In contrast to a builder, a method that can be invoked automatically when an object is released is called a destructor.

PHP4 supports destructors by logging on to a function called by register_shutdown_function () when the PHP run terminates, with only a similar method of implementation. PHP5 formally supports destructors that allow you to specify the actions of objects when they are released in the class.

A destructor is a method named __destruct. When the reference counter inside the object becomes 0, the __destruct () is invoked, and the memory used by the object is freed.

PHP Code:--------------------------------------------------------------------------------


Class Mydestructableclass {
function __construct () {
Print "in constructor\n";
$this->name = ' mydestructableclass ';
}

function __destruct () {
print ' destroying '. $this->name. "\ n";
}
}

$obj = new Mydestructableclass ();
?>

--------------------------------------------------------------------------------


In addition, the same place as the builder is that the destructor of the parent class cannot be invoked automatically, and, when necessary, the command is required:

Parent::__destruct ();

Access

In PHP4, if a non-existent property is accessed, the system automatically generates a new property corresponding to it.

PHP Code:--------------------------------------------------------------------------------
Class Hoge {
}

$obj = new Hoge;
$obj->prop = "This are new property";

--------------------------------------------------------------------------------



As shown above, when a value is taken into a nonexistent attribute, that surrogate point automatically generates a new attribute. Similarly, accessing a nonexistent property, like a variable that is being replaced by a null value, does not occur.

One additional point in PHP5 is the ability to control access to arbitrary properties. In a class where the __set (), __get () method is present, the method that replaces the above action will be able to be invoked. For example:

PHP Code:--------------------------------------------------------------------------------


Class Hoge {
function __set ($name, $value) {
Print "__set () is called with ($name, $value) \ n";
$this-> $name = $value;
}
}

$obj = new Hoge;

$obj->a = ' 123 ';
$obj->a = ' 456 ';
$obj->b = ' 789 ';
?>

--------------------------------------------------------------------------------


Here, the __set method is used as a surrogate method for undefined attributes, and values are replaced with undefined attributes after the value is displayed.

PHP Code:--------------------------------------------------------------------------------
$obj->a = ' 123 ';

--------------------------------------------------------------------------------


When executing this sentence, because there is no attribute A at this time, the __set method is invoked instead.

__set () is called with (A, 123)

Secondly

$obj->a = ' 456 ';

Once again to $obj->a, this time, because property a already exists, so __set is not invoked, and as usual the value is replaced with the attribute a.

$obj->b = ' 789 ';

This time, we put the value into another attribute B, the same as the first case of a,

__set () is called with (b, 789)

In contrast to the __set method, the __get method is called when a reference to a nonexistent property is invoked. Combine the two, and take a look at the access to the attributes, and in fact, use it to write classes that can respond differently on different occasions.

PHP Code:--------------------------------------------------------------------------------


Class Hoge {
Public $properties;

function __set ($name, $value) {
$this->properties[$name] = $value;
}
function __get ($name) {
return $this->properties[$name];
}
}

$obj = new Hoge;

$obj->a = ' 123 ';
$obj->b = ' 456 ';
Echo $obj->a;
Echo $obj->b;

Print_r ($obj);
?>

--------------------------------------------------------------------------------


In this example, access to all the properties in the class is loaded into the $properties so that the attributes we add are not directly attached to the object. This is an example that is not easy to understand, for example, it would be interesting to try to save the case to $properties to a file or database. In fact, within the object, we can simply implement a lot of complex operations.

Unlike __set, __get is somewhat different, but __call can also be used to write methods that do not exist, and when we call the object's methods like the following example,

$object->methodname ();

If the MethodName method does not exist in this class, the following error normally occurs:

Fatal error:call to undefined method Class::methodname ()

However, if there is a __call this method in this class, the __call is invoked as an alternative. __call has two parameters, the first parameter is the name of the method being called, and the second parameter is an array of the arguments that are called. In addition to the following examples, there are a number of other methods that can be used, given the many usage methods.

PHP Code:--------------------------------------------------------------------------------


Class Proxy {
Private $object;

function __call ($name, $params) {
if (Isset ($this->object)) {
if (method_exists ($this->object, $name)) {
return Call_user_func_array (Array ($this->object, $name), $params);
}
else {
Return ' method is not exists. ';
}
}
}
function __construct ($object) {
$this->object = $object;
}
}

Class Hoge {
function Add ($var 1, $var 2) {
Return $var 1 + $var 2;
}
}

$p = new Proxy (new Hoge);

$result = $p->add (1, 2);
echo "Result: $result
\ n ";

$result = $p->sub (5, 3);
echo "Result: $result
\ n ";
?>



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.