PHP::,,, Self, Parent::, $this operator differences

Source: Internet
Author: User
Tags php class

When accessing a member variable or method in a PHP class, if the referenced variable or method is declared as const (defining a constant) or static (declaring static), then the operator must be used::, conversely, if the referenced variable or method is not declared as const or static, Then you must use the operator---.

In addition, if you access a const or static variable or method from within a class, you must use self-referencing, and conversely, if accessing from within a class is not a const or static variable or method, you must use a self-referencing $this.

static variables
is a variable that exists only in the scope of a function, but the value of the variable is not lost after the function is executed, that is, the variable will still remember the original value the next time the function is called. To define a variable as static, simply precede the variable with the static keyword .

Use of static elements in a class
In a class, the static keyword has two main uses, one for defining static members and one for defining static methods . Within a class, you can use the scope qualifier (::) To access variables of different levels of scope.

Static Members
A static member is a class variable that can be viewed as abelongs to the entire classInstead of belonging to an instance of the class. Unlike a typical instance variable, a static member retains only one variable value, and the value of the variableis valid for all instances, in other words, all instances share this member.
$this represent only the current instance of the class,andSelf:: Represents the class itself, this operator cannot be used in code other than the class, and it does not recognize its position in the inheritance tree hierarchy.
In other words, the extension class uses the SelfScope, SelfA method declared in a base class can be called, but it is always called by methods that have been overridden in the extension class. And$thisThe difference is that when you use a static variable, you must add it after the scope qualifier$Symbol.
In an extension class, when the method of the base class is overridden, use theParentThe scope calls the method defined in the base class.static members can also belong to the parent class only. If you declare a member in both the subclass and the parent class, you can also use theparant::Accesses a variable in a parent class in a subclass. In this case, the static members of the parent class and the child class are saved with a different value.
You can access a member statically by writing the name of the class on the left side of the: operator, soavoid creating instances of classes. Not only the code that instantiates the class is omitted, but alsomore efficient, because each instance of the class consumes a fraction of the system resources.
When accessing member variables using:: operator, you need to pay attention to the$The use of symbols. Because PHP does not currently support the use of dynamic static variables, which means that mutable static variables are not supported. When using the $this-> $var, the member being accessed is the value of the variable contained in the $var.instead of accessing a variable without the $ symbol, you are actually looking for a constant of a class,and constants are not accessible through $this ..
Static in PHP6: scope makes it unnecessary for us to use Self:: and Parent::. When you want to point to a class that ultimately implements functionality, you can use static:: This qualifier calculates the members of the last class on the inheritance hierarchy immediately before the code executes. One process is called deferred binding, which allows us to override a static variable in a subclass, and can also ask the final member from a function declared in the parent class.

Static methods
There is an important difference between static and non-static methods: When you call a static method, you no longer need to have an instance of the class .
Static and non-static method usage principles :
First, if a method does not contain a $this variable, it should be a static method; If you do not need an instance of a class, you might also want to use a static class, which avoids the task of instantiating the class. Also, you cannot use the $this variable in a static method, because the static method does not belong to a particular instance.

When using scope-qualified operators in PHP, variables are not allowed when they are used as the name of the class.

    • Parent:: Can be used to invoke a member method defined in the parent class.
    • Parent:: Is traced not only to the immediate parent class.
Note:
There is no difference between $this->func () and Self::func () when inside a class.
Externally,,-> must be used as an instantiated object, while:: Can be called directly from an instantiated class name.
As an example:
Class mytest{
function CCC ($STR) {
Echo $str;
}
}
MYTEST::CCC ("123456");
$object = new Mytest ();
$object->CCC ("123456"

PHP is a very strange language. Of course, this is for people who have studied object-oriented languages such as C + + or java.
PHP can define a static method and then call it through the Classname::staticmethod () Form. Non-static method, of course, is used by Classobject->nonstaticmethod (). The same is true in other languages, no fuss. However, can you call non-static methods with Classname::nonstaticmethod ()? I am afraid that Java and C + + will be cold Sweat DC. In fact, PHP itself is also full face black line. Why do you say that?
Let's take a look at the object-oriented static and non-static. In object-oriented languages, static methods are supported. A static method that belongs to a class of fixed assets; a non-static method that belongs to the private property of an instance of a class. In memory, a static method has only one copy of the entire class; no matter how many instances you have new, they share the same share. For non-static is not the same, you new, memory will give you new several. In addition, non-static methods can not be called inside a static method, but static methods can be called inside a non-static method. This is the difference between static and non-static.
Object-oriented defines static with the static keyword. A method that is not marked as static is not invoked in the form of a class name plus two colons. PHP and other very different point is this: PHP is not marked as a static method, you can also use the class name plus two colons in the form of a call. So why does PHP have this syntax? Why do you feel so helpless?
-----The following instructions PHP helpless story according to the relevant information adapted, has been treated by the kingdoms--------
PHP has evolved so quickly, thanks to its speed. As a scripting language, PHP pursues high speed and simplicity, so it chooses to interpret execution and use process methods. Later, in order to conform with the international, the concept of object-oriented was introduced. And that is in the introduction of this object-oriented features, there has been an open PHP stunned, the ultimate helpless thing. An important concept of object-oriented is inheritance. In inheritance, if a subclass overrides a method of the parent class and needs to invoke the same name method of the parent class, what should I do? The PHP4 version provides a way to: Parentclassname::method (). When this approach is presented, insight has discovered the problem: Is this call method not just a static method invocation? PhP4 immediately replied: "Not in the way." When used in a class, it is possible to judge that this method is calling a parent class method for a subclass, and when used in a non-class, it is called a static call. All that is needed is to find out how to query the method mappings when this kind of call is made. In fact, a thought, it is really so. PhP4 later think, if each call to check whether the call is legitimate, that how much will affect performance, rather than this problem to the programmer to control it: they will know only in the class using this form of invocation. Alas, the day days wondering people wish. PHP4 underestimated the creativity of programmers! The programmers quickly discovered the way and used it with no force. Many integrated APIs are also starting to use this quirks approach. PHP is helpless, then introduced in php5 another way, using the keyword parent to call the parents function: Parent::method (). However, it is no longer possible to discard static calls to a non-static method of PHP.
--------------------------------------------------------
But, anyway, what is the advantage of this kind of PHP quirks? What about performance and memory footprint?
So I started to reason: defined a non-static method, when the static call, PHP first convert this method to static definition, load into the static memory area, and then execute. Usually once a business, using only one method in a business processing class, if the static call is used statically, does not the memory load only one of the methods in the business class, does it not implement the on-demand load of the static method? Do you want to save a bit of memory? In terms of performance, whether it's a static call or an object call, it's all about executing a method, and the performance is not the same. and statically invoking a non-static definition method also saves a new statement. Well, uh. At the same time, the hand began to write.
So how is it actually? I did a little test.

PHP Code
T::start (); T::end (); Eliminate the impact of the first load of T class
T::start ();
Model_profile_base::getbaseinfo ($UID);
T::end ();

T::start ();
$model = new Model_profile_base ();
$model->getbaseinfo ($UID);
T::end ();


T::start ();
$model = new Model_profile_base ();
$model->getbaseinfo ($UID);
T::end ();


Model_profile_base is a business class that deals with basic data, is more complex and is closer to the actual business process in the project.
The following is a definition of the T class used for timing and statistical memory:

PHP Code
<?php
function Microtime_float ()
{
List ($usec, $sec) = Explode ("", Microtime ());
return (float) $usec + (float) $sec);
}
Class t{
Static $start _time;
Static $end _time;
Static $start _memory;
Static $end _memory;

public static function Start ()
{
Self:: $start _memory = Memory_get_usage ();
Self:: $start _time = Microtime_float ();
echo ' <br/>start @ '. Self:: $start _time. ' ('. Self:: $start _memory. ') | -------> ';
}

public static function End ()
{
Self:: $end _time = Microtime_float ();
Self:: $end _memory = Memory_get_usage ();
echo ' End @ '. Self:: $end _time. ' ('. Self:: $end _memory. ') :‘;
Echo ' |======= a total time-consuming: '. (Self:: $end _time-self:: $start _time). ', Shared memory: '. (Self:: $end _memory-self:: $start _memory);
}
}

The second line is to statically call the non-static method, and the third line is to call the non-static method normally. Then I found out that my reasoning was tragic. Brush several times the page, the statistical results are similar in order of magnitude. Static calls to non-static methods are not flattering regardless of memory consumption or performance. The result is a bit raspberry.
Then, try the results of the loop execution multiple times:

PHP Code
T::start (); T::end (); Eliminate the impact of the first load of T class
T::start ();
for ($i =0; $i <1000;++ $i) model_profile_base::getbaseinfo ($UID);
T::end ();

T::start ();
$model = new Model_profile_base ();
for ($i =0; $i <1000;++ $i) $model->getbaseinfo ($UID);
T::end ();


So the result is more silent:

PHP Code
Start @1287562243.5799 (1009372) |------->end @1287562243.5799 (1009372): |======= total time: 3.0040740966797E-5, shared memory: 0
Start @1287562243.58 (1009372) |------->end @1287562244.1532 (1587544): |======= total time: 0.57321000099182, shared Memory: 578172
Start @1287562244.1532 (1587544) |------->end @1287562244.6921 (1587744): |======= total time: 0.53887605667114, shared memory: 200


There is still a world of difference in memory, in addition to the two ways in which the time begins to approach the outside (and the normal call is relatively neat). Disappointed, checked the internet, found that someone did a similar test. I'll just cuff the results:
(may see the result, will feel a bit difficult to understand, can find the detailed explanation here: http://vega.rd.no/articles/php-static-method-performance)

Test results (ORDER by Time DESC):

PHP Code
============which method========================time======
Inline calculation 0.0805 S
Normal function Call 0.3438 s
Normal method called through object 0.4118 s
Static method called statically 0.4280 s
Unspecified method called through object () 0.4294 s
Unspecified method called statically () 0.6960 s


In this sense, static calls to non-static methods do not have an advantage in performance and memory, and in addition, this method of invocation is prone to maintenance confusion. So, a short and powerful summary: static calls to non-static methods are undesirable.
Http://www.dabaoku.com/jiaocheng/biancheng/php/201102248955.shtml



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.