PHP basic tutorial 10 static attributes and static methods

Source: Internet
Author: User
This section describes static attributes and static method access modifier Singleton mode magic method class automatic loading.

Content described in this section
  • Static attributes and static methods

  • Access modifier

  • Singleton mode

  • Magic

  • Automatic loading of classes

Preface

In the previous section, we introduced the basic usage of object-oriented, but the knowledge in the previous section still cannot be solved in practice. for example, if we buy a ticket, there is a total number of votes (defined as the vote attribute), to buy a ticket (ticket-1), but each time we create an object, according to the way the object is in the memory, it is unreasonable to re-create a total number of votes. here we use the static concept. There are two types of static in PHP:

  1. Static attributes

  2. Static method

Static attributes

Static attributes are all objects of the class.Shared variablesWhen an object of this class accesses it, the same value is obtained. When an object of the same class modifies it, the same variable is modified.

 Name = $ name;} // defines a method to buy tickets. public function sellTicket () {echo $ this-> name .'
'; Self: $ number --; // The total number of votes for each method call is reduced by one. } $ Lele1 = new Ticket ('xiaobai'); $ people2 = new Ticket ('xiaoming '); $ people3 = new Ticket ('xiaohua '); $ people4 = new Ticket ('zhangzhang'); // each person buys a Ticket $ people1-> sellTicket (); $ people2-> sellTicket (); $ people3-> sellTicket (); $ people4-> sellTicket (); echo Ticket: $ number; // access static attributes outside the class by class name. ... Results... Tom bought a ticket. Tom bought a ticket. Hua bought a ticket. John bought a ticket. John bought a ticket. 96.

In the above code, you can see the definition of static attributes.

Access modifier static $ static property name = initialization value;

Static attributes can only be defined within the class.

Static attribute access

Outside the class

Outside the class, we can also use static attributes in the category class, just as we wrote above to directly access the class name (only when the permission modifier is public) Ticket :: $ number; Where: is a range parser.

You can also use objects to access static attributes outside the class.

$people4::$number;

Access through the class name is through the range parser: access.

In the class

In the code above, we can see that in the class, we access through the self: $ static attribute name. In addition to this method, there is also a way to access in the class.

Ticket::$number--;

Access by class name. The recommended format is self, because this method does not need to be modified after the class name is changed. So what is the difference between self and $ this?

$ The difference between this and self

In fact, the $ this mentioned in the previous section points to the currentObjectAnd here self is pointingCurrent class, One pointing to the object, one pointing to the class, pointing to different. At the same time, the two of them use different self:, $ this is->. However, both of them have the same applicability and are used inside the class.

Use of static attributes

In the above section, we only explained how to define static attributes and how to use them. When should I use static attributes. When we need to share a copy of data with all objects during project development, we should consider using static attributes.

Static attributes are also a property, so the difference between them and common attributes is:

  • When the keyword "static" is added to the property, it becomes a static property.

  • Static attributes belong to the class and all objects share the attributes.

  • Common attributes belong to a single object.

Note that, as shown above, static attributes can be accessed in non-static methods.;

Static method

As for static attributes, let's talk about static methods.

 Name = $ name;} public static function sayHello () {echo 'this is a static method
';} Public function info () {// use the static method self: sayHello () inside the class; // access Ticket: sayHello () through self (); // access by class name} $ people1 = new Ticket ('xiaobai'); $ people1-> info (); $ people1: sayHello (); // access Ticket: sayHello () through the object name outside the class; // access through the type. ... Result... this is a static method, this is a static method

Static methods are defined by the keyword static:

Access modifier static function method name (parameter list) {code ....}
Static method access

Outside the class

The access form of the static method outside the class is the same as that of the method for accessing the static attribute (the permission modifier can only be accessed externally if it is public ).

  • Access by class name: static method name

  • Object Name: static method name (not recommended)

  • Object Name> static method name. That is, the access method form.

In the class

The method for accessing static methods in a class is the same as that for accessing static properties.

  • Self: static method name

  • Class name: static method name

Use of static methods

So under what circumstances should we use static methods? We can use static methods when operating static properties.

  • When we need to operate static properties, we consider using

  • In php development, some modes are often used, such as Singleton mode, Factory mode, and observer mode. static methods are used.

Note: static methods cannot access non-static attributes.;

Access modifier

In the above code and instructions, we can see that there is a public in front of the attribute or in front of the method. this public is one of the access modifiers. An access modifier can be called to encapsulate objects.

Types and differences of access modifiers

The access modifier in PHP can be divided into three parts:

  1. In the code above, we use public. attributes and methods modified by this keyword can be accessed either inside the class or inside the class.

  2. If protected (protected) is modified using this keyword, it cannot be accessed outside the class. Access is allowed only within the class.

       Name = $ name; $ this-> age = $ age ;}$ cat = new Cat ('xiaobai', 4); echo $ cat-> name; // access public echo outside the class'
    '; Echo $ cat-> age; // access the protected attributes outside the class ....... Result... Fatal error: Cannot access protected property Cat ::$ age in D: \ mywamp \ Apache24 \ htdocs \ zendstudio \ yunsuanfu \ xiussce. php on line 16

    The error message indicates that the attribute modified by protected cannot be accessed.

  3. Private (private), which can only be used inside the class. if used outside, the same error will be reported.

These three types, the latter two seem to play the same role and can only be used within the class. what is the difference? Now it seems that there is no difference, but I have learned the inheritance of classes, so there is a difference between the two.
Use of access modifiers:

  • The access modifier must be specified for the member attribute. Otherwise, an error will be reported.

  • The modifier can be left blank before the method. the default value is public.

  • You can leave the access modifier unspecified for static properties. the default value is public.

Singleton mode

The above explains when to use static methods. In some design patterns, we can use static methods and static attributes.

Design Pattern: it is a set of summary of code design experiences that are repeatedly used, known by most people, classified and catalogued. The design pattern is used to make code reusable, make it easier for others to understand, and ensure code reliability. There is no doubt that the design pattern is win-win for others and the system; the design pattern enables code compilation to be truly engineered; the design pattern is the cornerstone of the software engineering, just like the structure of the building. (Baidu)

During development, we need to create an object in the code, but we hope that in a project, this object instance can only have one object and cannot create multiple objects, this protects databases and other resources. In this case, the singleton mode is used.

 ';} Public static function getInstance () {if (self: $ instance = null) {self: $ instance = new DaoMysql ();} return self :: $ instance;} public function insertSql () {echo 'add data
';}}$ DaoMysql = DaoMysql: getInstance (); $ daoMysql-> insertSql (); $ daoMysql2 = DaoMysql: getInstance (); $ daoMysql2-> insertSql ();...... result ....... add data to database connection

1. since it is a singleton mode, you cannot create objects externally. This requires the constructor to be modified using private (the constructor must be called to create an object. here, the constructor is private, in this way, objects cannot be created externally.
2. we have created an object reference $ instance in the class and created an object in the class. this is allowed.
3. to define a static method in a class, we create an object by using the class name: method name. after going in, we first determine whether $ instance is empty, we can only create an instance if it is null. Then return the object.
4. to access a property in a static method, the property should be a static property.
5. create an object using the class: static method name outside the class.
6. in the result, we can see that we have two objects, but the constructor is not executed for the second time, indicating that the object is not created.

Although we have made a lot of restrictions above, there are still Methods in PHP to get more objects, clone and inherit.

Object type operators

In the above static method, there is another way to determine whether an object is created.

if(!(self::$instance instanceof self)){                self::$instance = new DaoMysql();}

Instanceof is a type operator. Based on the help documentation, it has several functions

  1. Used to determine whether a PHP variable belongs to a class:

  2. It can be used to determine whether a variable inherits from an instance of a subclass of a parent class:

  3. It can also be used to determine whether a variable is an instance of an object that implements an interface:

In the above code, self represents the current class. Instanceof checks whether the preceding variable is an instance of the back class, and then obtains the inverse.

Magic

There are some magical methods defined in PHP in the class, called Magic methods. For details about how to use magic methods, refer to another blog.
PHP magic

Automatic loading of classes

We have discussed the introduction of files before, using the include and require types. During development, we sometimes need to introduce a large number of files, which can be 10 or 20. if we still use the original method, it will be tiring.

In PHP 5, this is no longer needed. You can define a _ autoload () function.Automatically called when trying to use a class that has not been defined.
When writing a class, we generally use a class as a file, and the file name is generally in the format of class name. class. php.

 Eat (); $ cat-> eat ();

_ Autoload ($ Class name), because a function is not written in a class, there is no permission modifier before it.

The above automatic loading method has limitations. this method obviously does not work when files are in different folders. In this case, you can create an array and store the class name as a key and the corresponding path as a value. It can be correctly introduced during automatic loading.

 '. /Dao/Dao. class. php', 'cat' => '. /cat/Cat. class. php '); // the automatic loading method. when we use a class that does not exist in this file, it will automatically load it. Function _ autoload ($ class_name) {global $ path; require_once $ path [$ class_name];} $ dao = new Dao ('xiaobai', 5 ); $ cat = new Cat ('floret, 2); $ dao-> eat (); $ cat-> eat ();

We can see that an array is defined before to store the path.
Note: global variables can be used only when global declaration is used in the function.

Summary

There are still many static attributes and static methods used in object orientation. At the same time, permission modifiers are very important in object orientation, because we control access permissions through modifiers. The master of magic methods also allows us to understand various conditioning mechanisms during access.

The above are the static attributes and static methods of PHP basic tutorial 10. For more information, see PHP Chinese website (www.php1.cn )!

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.