Php5_php for object-oriented

Source: Internet
Author: User
Keywords object orientation method function php property
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? Let's take a detailed look at the beta release of the PHP5 currently released.




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

The Zend Company, which developed the Zend Engine, was incorporated in the development of PHP4 by a company created by PHP3 's main developer Zeev Suraski and Andi Gutmans. The name of the Zend is made up of the names of Zeev and Andi. Zend's business model is to continuously provide the PHP core (core) of the Zend Engine for open source, while improving the benefits of developing and selling peripheral products. The business of using open source software as a base disk is a good example of the most struggling companies around the world.

The limitations of PHP4

With the success of PHP4, the scope of application for this use has gradually become wider. Using PHP as an enterprise-class use is something to hear. Therefore, there is a problem, when building a large-scale web site, the code is very poor re-use. Specifically, PHP4 's object-oriented performance is weak, so technicians accustomed to using Java have a lot to complain about.

Gradually improve the object-oriented performance of PHP4, greatly changing the basic grammar, the developer has reached the goal of updating the PHP description method.

Zend 2.0 started development
Subsequently, developers of the Zend Company's PHP Center published the idea of 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, object-oriented performance is greatly enhanced.
The current expansion of the PHP4 Zend engine is the same as that of the former PHP3. This means raising the major version number of the new language engine, clarifying the method objectives, and welcoming the praise from the development community.

The development of Ze2, like the previous Zend engine, is run in open source mode. The latest source code is fully disclosed on CVS because it is open-minded, and the discussion about development is very active.

Now Ze2 is decided to use the next version of PHP PHP5. The time for the final release is now undecided, but it should be beta release, according to the Zend Company's April 1, 2003 release of newsletter.


(ii) new features of PHP5

Next, look at the performance of the hardened PHP5 in order. The first is the most important object-oriented performance, and the entity properties of the class are greatly modified. This is just about the new features of the class.

· The reference transition for an object is the default
· Restrictions on introducing access attributes
· Limitations of introducing access methods
· Abstract classes and abstract methods
· Interface
· Final statement
· Name space
· In-Class constants
· class variables
· Unified Builder
· destructor (Distructor)
· Other ancillary features

The above content is based on the April 22, 2003 CVS on the registered version of the information written, before the official release, there is also the possibility of change.

Default reference transitions for objects

In PHP4, if $var2 = $var 1 When using variable $var1 as the entity object of the class, the copy of $var 1 is replaced in $VAR2. Obviously, $var 2 to point to the same object as $VAR1, it is necessary to write $var2 =& $var 1, must add & as a reference.
In PHP5, the object's generation will become an automatic reference transition. Other words
$var 2= $var 1, both point to the same object. If you want to bring copy to the same PHP4, you will apply the method of importing __clone ().
$var 2 = $var 1->__clone (); Here, clone is preceded by two consecutive "_"
(This is just the nature of the entity of the Class)


Restrictions on introducing access attributes

In PHP4 classes, along with properties and methods, you can freely access the inside and outside of the class without restriction. As a result, users cannot prevent inadvertent changes to properties.

And in PHP5, like C + + and Java, the import of private, protected, public three levels of access restrictions, so that class designers can use the properties and methods to limit the method. The following are the meanings of the various access restrictions.

· Public: Be free to refer to, change, anywhere inside and outside the class
· Private: Can only be referenced, changed in the method of this class
· Protected: Can be referenced and changed in this class and in the methods of another class that inherits the class. In addition, in the inherited class, you can write access to the specified.

The "Var" in PHP4, as in the past, has the same meaning as public. Here's an example, let's see how 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 are declared private, $var 2 and $VAR3 are protected. Here

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

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

If you attempt 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's $var2.

However, because the $hoge method is not private and protected, the following code works correctly, returning the values 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

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

Secondly, in order to be able to see the state of protected's properties, we try to create a class that inherits the 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 property is protected, the restriction of access from the subclass is determined by the property declaration of the child class. In Hoge2, because $VAR3 is declared public, Hoge2 's $var3 can be accessed from anywhere (the entity is Hoge1 $VAR3). Because $var1 is private in Hoge1, $var1 in the Hoge2 subclass is not inherited, and in Hoge2 it is possible to make a property named $var1, so it is important to differentiate 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 occurs if you refer directly to $var2 without using method.

Limitations of introducing access methods

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

· Public: can be called from anywhere
· Private: can only be called from within the method of this class
· Protected: can only be called from this class and the subclass method

The meaning here is the same as Java and C + +, please don't confuse it.

Abstract classes and abstract methods

Supports the same abstract classes and abstract methods as java. Abstract methods provide only a way to invoke the method name, not 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 will occur.

Fatal Error:cannot Instantiate abstract class ClassName

The actual example that produces 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 be combined with 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 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 is myexception message ';
}
}

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

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


Final statement

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

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

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


Examples of error generation:

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 Zend's April 1, 2003 message, it should be beta release now," but the result of the developer's internal discussion was that it was too early for beta and probably not beta release.

If you are interested in this trend, you can refer to the information published on news://news.php.net/php.version5.dev:372

In this file, PHP5 's release plan has returned to a blank sheet of paper, and on the other hand, the development of Zend Engine2 is underway. The release of PHP5 is basically looking forward to "come to the end of the year".

New features of PHP5

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

Name space

PHP5 supports name spaces. Therefore, we can load classes, variables, constants, functions in the name space.

In the scope of PHP4, there are only three categories within global, function, and class, so pay special attention to "pollute" global space if you are not careful. If we were to use namespaces, we would be able to separate variable namespaces in the package, so it would be easier to make a separate package.

Examples of usage are as follows:

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 ";

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


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

Name Space Name:: Object Name

But PHP5 's name space does not have to be nested in a different way from C + +.

Constant in class

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

Here the const is the appointment, so the necessary corrections are made when using 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 the two places within the class. In this case, the constant constant_value within the MyClass has a higher priority and is displayed as "class constant".

Object variables

Even if the class is not instantiated, the object variable can be initialized exactly as specified. Here's how to access it:

Class Name:: $ variable Name

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


Class Hoge {
static $my _static = 5;
}

Print Hoge:: $my _static;
?>

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


Unified Builder

The method that can be called automatically when the object is generated is called the "builder".

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

In PHP, the builder of the parent class cannot be called automatically, so the situation is much more.
In PHP5, the __constructor is used as the builder name, 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 a previous builder name with the same class name, then the builder is preferred.

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 ();
?>

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


Destructors

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

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

A destructor is a method named __destruct. When the reference counter inside the object becomes 0, __destruct () is called, 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, in the same place as the builder, the destructor of the parent class cannot be called automatically, and the command is required when necessary:

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 is the new property";

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



As shown above, when the value is taken into a nonexistent property, the generation of the in point will automatically generate a new attribute. Similarly, accessing a nonexistent property is like a variable that has been replaced with a null value, and no error occurs.

One additional point in PHP5 is the ability to control access to arbitrary properties. In a class, if there is a method such as __set (), __get (), instead of the above action, the method here will be able to be called. 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 an alternative to the undefined attribute, and the value is replaced with an undefined attribute after the value is displayed.

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

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


When executing this sentence, because there is no property A at this time, therefore, as a substitute, the __set method is called.

__set () is called with (A, 123)

Secondly

$obj->a = ' 456 ';

Once again the $obj->a, this time, because the property a already exists, so __set is not called, and usually the same as the value into the attribute a.

$obj->b = ' 789 ';

This time, we put the value into another attribute B, as in 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 present. Combine the two and take a look at the access to the property, and actually 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 change the save in this example to $properties to a file or database. In fact, in 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 non-existent methods, when we call the method of the object as in the following example,

$object->methodname ();

If the MethodName method is not present in this class, the following error will normally occur:

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

However, if the __call method exists in this class, the __call is called as an alternative. The parameters of the __call are two, the first parameter is the named method name, and the second parameter is the array of the called arguments that are persisted. Considering that there are many ways to use it, other methods can be used in addition to the following examples.

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 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.