Keyword and magic methods in PHP

Source: Internet
Author: User
Tags autoload object serialization
In php, magic methods and keywords are commonly used. keywords include final, static, const, magic method _ call (), _ toString (), and _ clone (), _ autoload () and so on...

In php, magic methods and keywords are commonly used. keywords include final, static, const, magic method _ call (), _ toString (), and _ clone () and _ autoload.

Common keywords in PHP

Final

1. final can only modify classes and methods, but cannot modify member Attributes. function: a modified class cannot be inherited, and a modified method cannot be overwritten.

PHP 5 adds a final keyword. If the method in the parent class is declared as final, the subclass cannot overwrite the method. if a class is declared

Final, it cannot be inherited.

Example #1 Final method Example

The code is as follows:

Class BaseClass {
Public function test (){
Echo "BaseClass: test () called \ n ";
}

Final public function moreTesting (){
Echo "BaseClass: moreTesting () called \ n ";
}
}

Class ChildClass extends BaseClass {
Public function moreTesting (){
Echo "ChildClass: moreTesting () called \ n ";
}
}
// Generate Fatal error: Cannot override final method BaseClass: moreTesting ()
?>
Example #2 Final class Example

Final class BaseClass {
Public function test (){
Echo "BaseClass: test () called \ n ";
}

// No matter whether you declare the method as final.
Final public function moreTesting (){
Echo "BaseClass: moreTesting () called \ n ";
}
}

Class ChildClass extends BaseClass {
}
// Generate Fatal error: Class ChildClass may not inherit from final class (BaseClass)
?>


Static

1. you can use static to modify member attributes and member methods, but not classes.
2. the member attributes modified with static can be shared by all objects of the same class.
3. static data is stored in the data segment in the memory (initial static data segment)
4. static data is allocated to the memory when the class is loaded for the first time, and can be directly used later.
5. as long as the class name appears in the program, that is, the class is loaded, static data will be allocated to the memory. note: static members must access the class name.

Q: No need to create an object. do not use an object to access static members. Access Method class name: If a static member is used in the class, you can

Use self to represent the class access method self: static member
6. the static method cannot access non-static members. The non-static method can access static members because non-static members must use objects for access, but static members do not need

Yes

Example 1

The code is as follows:

Function test ()
{
Static $ var1 = 1;
$ Var1 + = 2;
Echo $ var1 .'';
}

Test ();
Test ();
Test ();
?>

Example 2

Example:

The code is as follows:

Class Person {
// Define static member attributes
Public static $ country = "China ";
// Define the static member method
Public static function myCountry (){
// Static member attributes for internal access
Echo "I am". self: $ country. "person
";
}
}
Class Student extends Person {
Function study (){
Echo "I am". parent: $ country. "person
";
}
}
// Output the member property value
Echo Person: $ country ."
"; // OUTPUT: China
$ P1 = new Person ();
// Echo $ p1-> country; // incorrect syntax
// Method for accessing static members
Person: myCountry (); // output: I am a chinese
// Static methods can also be accessed through objects:
$ P1-> myCountry ();

// Outputs the member attribute values in the subclass.
Echo Student: $ country ."
"; // OUTPUT: China
$ T1 = new Student ();
$ T1-> study (); // output: I am a chinese
?>

Run this example and output:

China
I am a chinese
I am a chinese
China
I am a chinese


First, we know that PHP calls the instance method through someobj-> someFun (), so can we call static functions like C #?

What if I call it through SomeClass-> someFun? The answer is No. in PHP, the call to static members can only be done through:, for example:

SomeClass: someFun ().

The code is as follows:
Class TestC
{
Public static $ var1 = 1;
Public $ var2 = 1;
Function t1 ()
{
Self: $ var1 + = 2;
Echo self: $ var1 .'';
Echo $ this-> var2 .'';
}
Public static function t2 ()
{
Self: $ var1 + = 2;
Echo self: $ var1 .'';
}
}
$ T = new TestC ();
$ T-> t1 ();
TestC: t2 ();
?>

Const
1. const can only modify member attributes
2. use const to declare constants in the class
3. usage is similar to defining general constants
4. the access method is the same as that of static members (in the out-of-class name: constant name, class self: constant name)
5. constants must be declared with the initial value.

Syntax:

Const constant = "value ";
Example:

The code is as follows:

Class Person {
// Define a constant
Const country = "China ";

Public function myCountry (){
// Internal access constant
Echo "I am". self: country. "person
";
}
}

// Output constant
Echo Person: country ."
";

// Access method
$ P1 = new Person ();
$ P1-> myCountry ();
?>

Run the sample output:

China
I am a chinese


Common PHP magic methods:

_ Call () is used to call a method that does not exist in an object. The system reports an error and the program exits. Declare this method

To prevent program crashes.

_ ToString () is called when an object reference is directly output. it is the most convenient way to quickly obtain the string representation of an object.

The code is as follows:

// Declare a simple class
Class TestClass
{
Public $ foo;

Public function _ construct ($ foo)
{
$ This-> foo = $ foo;
}

Public function _ toString (){
Return $ this-> foo;
}
}

$ Class = new TestClass ('Hello ');
Echo $ class;
?>


Void _ clone (void)
When the replication is complete, if the _ clone () method is defined, the _ clone () method in the newly created object (the copied object) will be called.

Used to modify the attribute value (if necessary ).

The code is as follows:

Class SubObject
{
Static $ instances = 0;
Public $ instance;

Public function _ construct (){
$ This-> instance = ++ self: $ instances;
}

Public function _ clone (){
$ This-> instance = ++ self: $ instances;
}
}

Class MyCloneable
{
Public $ object1;
Public $ object2;

Function _ clone ()
{

// Force copy this-> object; otherwise, it still points to the same object
$ This-> object1 = clone $ this-> object1;
}
}

$ Obj = new MyCloneable ();

$ Obj-> object1 = new SubObject ();
$ Obj-> object2 = new SubObject ();

$ Obj2 = clone $ obj;


Print ("Original Object: \ n ");
Print_r ($ obj );

Print ("Cloned Object: \ n ");
Print_r ($ obj2 );

?>

_ Autoload () other magic methods are added to the class. this is the only method not added to the class, as long as it is used on the page.

To a class, as long as the class name is used, it will be automatically passed into this method

The code is as follows:

Session_start ();
Require_once 'myclass. php ';
$ Obj = new MyClass;
$ _ SESSION ['obj '] = $ obj;
?>

Works fine. Then on a subsequent page load:

The code is as follows:

Session_start ();
Require_once 'myclass. php ';
$ _ SESSION ['obj ']-> callSomeMethod ();
?>

Fatal error: The script tried to execute a method or access a property of an incomplete object. Please

Ensure that the class definition "MyClass" of the object you are trying to operate on was loaded

_ Before _ unserialize () gets called or provide a _ autoload () function to load the class definition.

But if you do this instead, it works fine:

The code is as follows:

Require_once 'myclass. php ';
Session_start ();
$ _ SESSION ['obj ']-> callSomeMethod ();
?>


Object Serialization: convert an object to a binary string. 1. store the object for a long time in a database or file. 2. Upload the object to multiple php files.

Serialize (): the parameter is an object, and a binary string unserialize () is returned: the parameter is the binary string of the object, and The Returned is

The new object _ sleep () is automatically called during serialization (serialize): You can serialize part of an object as long

This method returns a data group. Several member attributes are serialized in the array. If this parameter is not added, all member attributes are serialized.

_ Wakeup () the method automatically called during deserialization (unserialize) is a process in which the object is re-generated.

Note: PHP regards all class methods starting with _ (two underscores) as magic methods. So when you define a class method, in addition to the above magic method,

We recommend that you do not use _ as the prefix.



Tutorial link:

Reprint at will ~ However, please keep the tutorial address★

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.