PHP Basic Tutorial 10 static properties and static methods

Source: Internet
Author: User

What this section explains

    • static properties and Static methods

    • Access modifiers

    • Single-Case mode

    • Magic method

    • Automatic loading of classes


In the previous section, we introduced the basic object-oriented use, but the knowledge in the last section, in fact, there are problems can not be solved, such as we go to buy tickets, there is a total number of votes (the definition of the ticket), to a person to purchase a ticket (Ticket-1), but each time we create an object, according to the is to re-create a total number of votes, this is not reasonable, here we use the concept of static, in PHP class static is divided into two kinds:

    1. Static properties

    2. Static methods

Static properties

A static property is a variable shared by all objects of that class, and any object of that class accesses it by the same value, and the same variable is modified when any object of that class modifies it.

<?php    class ticket{public        static $number = 100;//Set the total number of votes is; public        $name;         Public function __construct ($name) {            $this, name = $name;        }        Define a method for buying tickets public        function Sellticket () {            echo $this-name. ' Buy a ticket <br> ';            Self:: $number--; The total number of votes per call is reduced by one.        }    }    $people 1 = new Ticket (' small white ');    $people 2 = new Ticket (' xiaoming ');    $people 3 = new Ticket (' Xiao Hua ');    $people 4 = new Ticket (' Xiao Zhang ');    Everyone to buy tickets    $people 1-sellticket ();    $people 2, Sellticket ();    $people 3, Sellticket ();    $people 4, Sellticket ();    echo Ticket:: $number; Static properties are accessed through the class name outside the class.    ...... The result ...    .. Xiao Bai bought a ticket and Xiao Hua bought a ticket to buy a ticket for the small    Zhang    96

You can see how static properties are defined in the code above.

Access modifier static  Property name = initialization value;

A static property can only be defined inside a class.

Access to static properties

Outside the class

Outside of the class, we can also access the static properties in the class, as written above, directly through the class name (only if the permission modifier is public) Ticket:: $number; Where:: Is the range resolver.

You can also access static properties through objects outside of the class

$people 4:: $number;

Access through the class name is through the scope resolver:: Access.

Inside the class

In the above code, we can see that in the class we access it by self::$ the static property name. In addition to this approach, there is a way to access it in the class.

Ticket:: $number--;

Accessed through the class name. The recommended format is through self, because this way, when our class name changes, we don't have to change it. So what's the difference between self and $this?

The difference between $this and self

In fact, in the last section of the $this, is pointing to the current object , and here self is pointing to the current class , a pointer to the object, a pointer to the class, pointing to the different. At the same time, they both use the same way. Self is two::, $this is. However, the application of the two is the same, which is used internally within the class.

Use of static properties

In the above we just explained the method of defining static properties and how to use them, as well as when to use static properties. When we need to have all the objects share a single piece of data in project development, we consider using static properties.

A static property is also a property, so the difference between it and the normal property is:

    • Property plus static is the key, and it will turn into a statically property.

    • Properties of a static property belonging to the class, shared by all objects

    • Normal properties belong to a single object.

note that, as in the above, static properties can be accessed in non-static methods. ;

Static methods

The static properties are described above, so let's talk about static methods next.

<?php    class ticket{public        static $number = 100;//Set the total number of votes is; public        $name;         Public function __construct ($name) {            $this, name = $name;        }        public static function SayHello () {            echo ' This is static method <br> ';        }        Public Function info () {            //Use static method Self::sayhello () Inside the class,//            access            Ticket::sayhello () through self;// Access by class name        }    }    $people 1 = new Ticket (' small white ');    $people 1, info ();    $people 1::sayhello (); Access by object name outside the class    Ticket::sayhello ();  Accessed through a type.    ...... The result ...    .. This is a static method which is static method which is static method    which is static method

Static methods are defined in the form of a keyword static:

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

Access to static methods

Outside the class

Static methods are accessed outside the class in the same way that they access static properties (the permission modifier is only public and can be accessed externally).

    • Access by class Name:: Static method Name

    • By object name:: Static method Name (not recommended)

    • static method name, by object name. That is, the form of the access method.

Inside the class

It is also the same way to access static methods in a class and to access static properties.

    • Self:: Static method Name

    • Class Name:: Static method Name

Use of static methods

So, under what circumstances do we use static methods? We can use static methods when manipulating static properties.

    • When we need to manipulate static properties, we consider using the

    • In our PHP development, we often use a number of patterns, such as singleton mode, Factory mode, observer mode, etc., using static methods.

Note: Static methods cannot access non-static properties ;

Access modifiers

In the above code and in the description, we can see that either before the property or before the method there is a public, the public is one of the access modifiers. An access modifier can be said to be a way to implement an object encapsulation.

Classification and distinction of access modifiers

Access modifiers in PHP can be divided into three

    1. Public in the above code we are all using the public, using this keyword decorated properties and methods, whether inside the class or inside the class is accessible.

    2. protected (Protected) If you use this keyword modifier, you cannot access it outside of the class. Access can only be made within the class.

      <?php    class cat{public        $name;        protected $age;        Public function __construct ($name, $age) {            $this, name = $name;            $this, age = $age;        }    }    $cat = new Cat (' Small white ', 4);    Echo $cat, name; Access public    echo ' <br> ' outside the class;    Echo $cat, age; The protected decorated property is accessed outside of the class. ...... Results..... Small white fatal Error:cannot Access protected property Cat:: $age in D:\mywamp\Apache24\htdocs\zendstudio\yunsuanfu\ xiushifu.php on line 16

      The wrong message is that you cannot access the properties of the protected adornment.

    3. Private, which can only be used inside the class, is used externally to report the same error as above.

What is the difference between these three, and the other two that look the same, which can only be used within the class? Now it seems that there is no difference, but learn the inheritance of the class, then the two are still different.

Use of access modifiers:

    • The member property must have an access modifier, or an error will be made

    • Method can be preceded by a non-write modifier, which is public by default

    • Static properties can not specify an access modifier, which is public by default

Single-Case mode

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

Design pattern: is a set of repeated use, most people know, after the purpose of classification, code design experience Summary. Design patterns are used in order to reuse code, make code easier for others to understand, and ensure code reliability. There is no doubt that design patterns in others in the system are multi-win; Design patterns make code production truly engineering; Design patterns are the cornerstone of software engineering, like the structure of a building. Baidu

At the time of development, we have the need to create an object in our code, but we hope that in a project, this object instance can have only one and cannot create multiple objects, thus protecting the resources such as the database. In this case, the singleton mode is used.

<?php class daomysql{public $link;//analog database connection private static $in        stance;//the object of the current class.        Private Function __construct () {echo ' database connection <br> '; } public static function getinstance () {if (self:: $instance = = null) {self:: $instance = NE            W Daomysql ();        } return Self:: $instance;        } public Function Insertsql () {echo ' Add data <br> ';    }} $daoMysql = Daomysql::getinstance ();    $daoMysql-Insertsql ();    $daoMysql 2 = daomysql::getinstance ();    $daoMysql 2, Insertsql (); ......    Results....... Database connection Add data add data 

1. Since it is a singleton pattern, it is not possible to create objects externally, it is necessary to use the constructor with private (create object to call the constructor, where the constructor is privatized, not called up), so that the object cannot be created externally.
2. We create a reference $instance for an object inside the class, which is allowed to create objects within the class.
3. Define a static method in the class, we create the object by this method, through the class name: The name of the method is created, in the first to determine whether $instance is empty, only if empty when we create. The object is then returned.
4. Because you want to access a property in a static method, this property should be a static property.
5. Outside the class, create the object through the class:: Static method name.
6. In the results we can see that we have two objects, but the construction method is not executed the second time, stating that the object was not created.

Although we have made a lot of restrictions on the above, there are methods in PHP to more objects, clones and inheritance.

Object Type Operators

There is also a way to determine whether an object is created in the static method above.

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

Where instanceof is the type operator. Depending on the help document, it has several functions

    1. Used to determine if a PHP variable belongs to an instance of a class class:

    2. Can be used to determine whether a variable is inherited from an instance of a subclass of a parent class:

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

The self in the code above represents the current class. instanceof determines whether the preceding variable is an instance of the following class, and then takes the inverse.

Magic method

In PHP There are some magical methods defined in the class, called Magic methods. The use of a specific magic method can be seen in another blog post
The Magic Method of PHP

Automatic loading of classes

In the previous we talked about the introduction of the file, using both the include and require types. In development we sometimes need to introduce a large number of files, can be 10 or 20, if you still use the original method, tiring.

In PHP 5, this is no longer necessary. You can define a __autoload () function that will be called automatically when you try to use a class that is not already defined .
While we are writing classes, is generally a class of a file, and the name of the file we are generally the class name. class.php format.

<?php    //Automatic loading method, when we use this file does not exist in the class, it will automatically load.    function __autoload ($class _name) {        require_once './'. $class _name. '. class.php ';    }    $dao = new Dao (' Small White ', 5);    $cat = new Cat (' Floret ', 2);    $dao-Eat ();    $cat-Eat ();

__autoload ($ class name), in which a function is not written in a class, is preceded by a permission modifier.

The above automatic loading method is limited, when the file is in a different folder, this method is obviously not possible. At this time, you can create an array, the class name as a key, the corresponding path as a value, to store. It can be introduced correctly when it is loaded automatically.

<?php    $path = Array (            ' Dao ' = './dao/dao.class.php ',            ' Cat ' = './cat/cat.class.php '        );    The automatic loading method is loaded automatically when we use a class that does not exist in this file.    function __autoload ($class _name) {        global $path;        require_once $path [$class _name];    }    $dao = new Dao (' Small White ', 5);    $cat = new Cat (' Floret ', 2);    $dao-Eat ();    $cat-Eat ();

You can see that an array is defined earlier to store the path.
Note: You can use global variables in a function to declare it.


There is still a lot of time to use static properties and static methods in object-oriented. At the same time, the permission modifier is important in object-oriented because we control access through modifiers. The mastery of magic methods can also allow us to understand the various conditioning mechanisms in the interview.

The above is the PHP basic tutorial 10 static properties and static methods of content, more relevant content please pay attention to (!

  • Related Article

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