Home >Backend Development >PHP Tutorial >PHP object-oriented static methods, properties and constants

PHP object-oriented static methods, properties and constants

不言
不言Original
2018-06-06 09:53:551884browse

This article mainly introduces the static methods, properties and constants about PHP object-oriented, which has a certain reference value. Now I share it with you. Friends in need can refer to it

Static methods , attribute

Definition

Use the static keyword definition;

Declare the class attribute or method as static, that is, you cannot Instantiate, access directly.

Note:

1) Static properties cannot be accessed through instantiated objects;

2) Static methods can be accessed;

3) Static methods , cannot use $this

Usage method

 :: 或  self::

The details are as follows:

  访问位置           调用属性           调用方法

类的内部/外部       类名::属性名      类名::方法名

   内部           self::属性名      self/类名::方法名

Comprehensive example

<?php

class MyClass
{
    // 静态属性
    public static $a = &#39;static&#39;;

    // 静态方法
    public static function func1()
    {
        echo &#39;静态方法&#39;;

        // 类的内部调用静态属性
        echo MyClass::$a;
        echo self::$a;

        // 类的内部调用静态方法
        MyClass::func2();
        self::func2();
    }

    // 试验静态方法调用另一个静态方法
    public static function func2()
    {
        echo &#39;This is static function 2.&#39;;
    }
}

// 类的外部调用静态属性、方法
echo MyClass::$a;
MyClass::func1();

// 实例化后再调用
$me = new MyClass();

echo $me::$a;   // 调用成功
// echo $me ->a;   调用失败
$me -> func1();  // 调用成功

Constant

constYou can define values ​​that remain unchanged in a class as constants.

The value of a constant must be a fixed value.

Call method, same as static.

Example

class MyClass
{
    public static $a = &#39;abc&#39;;
    const NUM = 123;
}

echo MyClass::$a;
echo &#39;<br/>&#39;;
echo MyClass::NUM;
echo &#39;<br/>&#39;;

// 修改静态属性
MyClass::$a = &#39;def&#39;;
echo MyClass::$a;
echo &#39;<br/>&#39;;

// 修改常量
//MyClass::NUM = 234;  赋值失败

Related recommendations:

php object-oriented constructor and destructor

php object-oriented encapsulation

php object-oriented classes and instantiated objects

The above is the detailed content of PHP object-oriented static methods, properties and constants. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn