Home  >  Article  >  Backend Development  >  Difference between const, static, public, private and protected in PHP

Difference between const, static, public, private and protected in PHP

little bottle
little bottleforward
2019-04-17 16:36:032424browse

const: Define constants, generally cannot be changed after definition

static: static, class name can be accessed
public: means global, can be accessed by subclasses inside and outside the class;
private: means private, can only be used within this class;
protected: means protected, can only be accessed by this class or subclass or parent class;

defined constants are also available" define"define.

The differences between const and define when defining constants are as follows:

1. const is used for class member variables and cannot be modified once defined. Define is used for global constants and cannot be used for class member variables. Definition,
const can be used in classes, define cannot.
2. Constants defined by const are case-sensitive, and define can specify whether case-sensitivity is achieved through the third parameter (TRUE indicating case-insensitivity).
Define a constant at runtime. define('TXE',100,TRUE);
3. const cannot define constants in conditional statements, but the define function can. if($a>10){define('LE','hello');}


##

class Demo
{
    //定义常量【自php5.3后】,一个常量是属于一个类的,而不是某个对象的
    //不可改变的
    const EVENT = 'const';
    static $event = 'static';
    public $eventPublic = 'public';
    private $eventPrivate = 'private';
    protected $eventProtected = 'protected';
    public function test()
    {
        //使用self访问类中定义的常量
        echo self::EVENT.&#39;<br/>&#39;;
        //同常量一样使用self
        echo self::$event.&#39;<br/>&#39;;
        //公共变量,受保护的变量,私密的变量通过$this访问
        echo $this->eventPublic.&#39;<br/>&#39;;
        //受保护的和私密的变量只能在当前类中访问
        echo $this->eventPrivate.&#39;<br/>&#39;;
        echo $this->eventProtected.&#39;<br/>&#39;;
    }

    //魔术方法
    public function __get($name)
    {
        return $this->$name;
    }
}

class One extends Demo
{

    public function testOne()
    {
        //可继承父级使用parent访问
        echo parent::EVENT.&#39;<br/>&#39;;
        echo parent::$event.&#39;<br/>&#39;;
        //也可通过父类直接访问
        echo Demo::EVENT.&#39;<br/>&#39;;
        echo Demo::$event.&#39;<br/>&#39;;
        //继承父级中的成员变量后,只能访问公共变量
        //私有变量和受保护的变量不能在子类中访问
        echo $this->eventPublic;
    }
}
$obj_1 = new Demo;
$obj_1->test();
echo "=================<br/>";
$obj = new One;
$obj->testOne();

Run result:


const
static
public
private
protected
=================
const
static
const
static
public

Related tutorials:

PHP video tutorial 

The above is the detailed content of Difference between const, static, public, private and protected in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete