PhP4's true oo

Source: Internet
Author: User

PhP4's true oo

Author Johan Persson is the developer of the famous jpgraph chart class library in PHP. This article is a summary of several small issues that need to be paid attention to during object-oriented development in PhP4.
Translation: binzy Wu [mail: binzy at justdn dot com]. The level is limited. Welcome to explore.-2-4.

Introduction
The objects in this article are those previously used more mature OO [1] languages, such as Eiffel, Java, C # [2] or C ++ (), development friends (such as myself ). there are many semantics when using PhP4 for full OO development [3] (semantic)
On the trap [4].

I hope this article will help you avoid the mistakes I made.

Reference vs copy Semantics
This is basically the main source of errors (at least for me ). even if you can read in PHP documents that PhP4 uses more copy semantics than references (for example, other object-oriented languages I know ), but it will still make you suffer from some minor problems.

The next two parts are used to illustrate two small examples. In these two examples, copying semantics may surprise you.

It is important to keep in mind that a class variable is not a pointer to the class, but the actual class itself [5]. most problems lead to misunderstanding of the value assignment operator (=), that is, to give an object an alias, but in fact it is a new copy. for example, suppose $ myobj is an instance of a class and it has a set () method. then the followingCodeMaybe not like a C ++ (or Java)ProgramThe employee expects to work as expected.

Function somefunction ($ aobj) {$ aobj-> set (10 );}
...
Somefunction ($ myobj );
...

Now, it is easy to think that the Set () method called by this function will act on $ myobj. But this is wrong!

In fact, $ myobj is copied as a new one, which is the same as the original object ---- parameter $ aobj. then, when the Set () method is called, it only acts on the local copy instead of the original parameter ---- $ myobj.

A variety of the above problems occur in places that contain direct or indirect (as shown above) Assignment operations.

In order for a function to act as you expected (maybe), you have to modify the method declaration to tell PHP to use references to pass objects, such:
Function somefunction (& $ aobj)

If you try the above Code again, you will find that the Set () method will act on the original parameter, because now we have created a $ myobj alias ---- $ aobj.

But you have to be careful, because even the & operator can not save you at any time, as shown in the following example.

Obtain a reference from a reference

Assume the following code is available:
$ Myobject = new someclass (); $ myreftoobject = & $ myobject;

If we want to copy a reference (for some reason), what should we do? You may try to write $ myreftoobject because it is already referenced:
$ Mycopyreftoobject = $ myreftoobject;

Correct? No! PHP will create a new copy of the object referenced by $ myreftoobject. If you want to copy an object reference, you have to write the following:
$ Mycopyreftoobject = & $ myreftoobject;

In the C ++ example that is equivalent to the preceding example, a reference is created. different from PHP. this is an intuitive assumption that experienced C ++ programmers often make is the opposite, and this will be the source of bugs in your PHP program.

Please be careful with the indirect (passing parameters) or direct problems arising therefrom.

My personal conclusion is that the best way to avoid these semantic traps is to always use references to pass objects or assign values to objects. this not only improves the Running Speed (less data copies), but also makes semantics more predictable for old dogs like me.

Use reference for $ this in the constructor

Initializing an object as an object discoverer (Observer [6]) in an object constructor is a common pattern. The following code is an example:
Class bettery
{
Function bettery (){...};
Function addobserver ($ method, & $ OBJ)
{
$ This-> obs [] = array ($ OBJ, & $ method)
}
Function notify (){...}
}
Class display
{
Function display (& $ batt)
{
$ Batt-> addobserver ("batteryy y", $ this );
}
Function batterynotify (){...}
}

However, this does not work normally. If you instantiate an object like this:
$ Mybattery = new battery (); $ mydisplay = New Display ($ mybattery );

The error is that $ this in the new constructor does not return the same object. instead, a copy of the recently created object is returned. that is, when addobserver () is called, the object transmitted is not the same as the original object. then when the battery class tries to notify all its observer (observer) (by calling their notify method, it does not call the display class we created, but the class represented by $ this (that is, copying the display class we created ). therefore, if the notify () method updates some instance variables, it is not as expected that the original display class will be updated, because the update is actually a copy. to make it work, you must make the constructor return the same object, as represented by $ this at the beginning. you can add the & symbol to the display structure, for example, $ mydisplay = & New Display ($ mybattery );
A direct result is that any display client must understand the display implementation details. in fact, this creates a question that may cause controversy: the construction of all objects must use additional & symbols. what I said is basically safe, but ignoring it may sometimes give the desired effect as shown in the preceding example.

Another solution is used in jpgraph. that is, you need to add a "Init ()" that can be safely used & $ this reference () "the so-called two-stage constructor of the method" new "is an object (only because $ this reference in the constructor returns a copy of the object and is not executed as expected ). therefore, the above example will be implemented as follows:
$ Mybattery = new battery ();
$ Mydisplay = New Display ();
$ Mydisplay-> Init ($ mybattery );

For example, the "linearscale" class in jpgraph. php.

Use foreach

Another issue with similar code but different results is the issue of the "foreach" structure, which studies different versions of the two loop structures in the pipeline.
// Version 1
Foreach ($ this-> plots as $ P)
{
$ P-> Update ();
}
...

// Version 2
For ($ I = 0; $ I <count ($ this-> plots); ++ $ I)
{
$ This-> plots [$ I]-> Update ();
}

Now it's a question worth $10 [7]: Version1 = version2?

The surprising answer is: no! This is a small but key difference. In version 1, the update () method will act on copies of objects in the "plots []" array. Therefore, the original objects in the array will not be updated.

In version 2, the update () method will act as expected on the objects in the "plots []" array.

As stated in the first part, this is the result of PHP processing the object instance as the object itself rather than as the object reference.

Note:
[1]. OO: object-oriented, object-oriented.
[2]. the original Article does not contain C #, because of binzy's personal interests.
[3]. semantic is translated as "semantic" in this article. If you have any suggestions, contact binzy.
[4]. c ++ has a famous "C ++ gotchas ".
[5]. the class here should refer to instance, that is, instance.
[6]. see [gof95], that is, design patterns ".
[7]. there is an interesting story about transactions:
someone bought a horse for $60 and sold it for $70. Then, he bought it back for $80 and sold it for $90. in this horse transaction, he? (A) lost $10; (B) Balance of Payments; earned $10; (d) earned $20; (e) earned $30.
This is a simple arithmetic exercise for college students, such as Mel and Bock, a psychologist at the University of Michigan. as a result, less than 40% of college students can make the correct answer. Most people think that they only earned 10 dollars. in fact, the condition for the problem is very clear. This is two transactions, earning 10 dollars each time, but many people mistakenly think that when he bought it back with 80 dollars, he had lost 10 dollars. interestingly, the same problem was raised in another way: one person bought a white horse for $60 and sold it for $70. Then, I bought a dark horse for $80 and sold it for $90. in this deal, he ____ (listing the same five choices ). at this time, when the other group of college students answered the above questions, they all answered correctly.

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.