首页> 基础笔记 >PHP基础学习 >面向对象 面向对象

PHP面向对象const关键字

作者:小萝卜 2019-09-02 浏览 1024

简介const是一个在类中定义常量的关键字,我们都知道在PHP中定义常量使用的是”define()”这个函数,但是在类里面定义常量使用的是”const”这个关键字

PHP面向对象const关键字

const是一个在类中定义常量的关键字,我们都知道在PHP中定义常量使用的是”define()”这个函数,但是在类里面定义常量使用的是”const”这个关键字

const只能修饰的成员属性(常量属性),其访问方式和static修饰的成员访问的方式差不多,也是使用”类名”,在方法里面使用”self”关键字。但是不用使用”$”符号,也不能使用对象来访问。 

const CONSTANT =‘constant value’;  //定义
echo self::CONSTANT;        //类内部访问
echo ClassName::CONSTANT;   //类外部访问

定义格式:
const 常量名  = 常量值;

常量的值可以是 int bool  float string null

访问形式;
内的内部  self::常量名
内的外部  类名::常量名 

实例:
<?php
//类中常量定义:const

class Game{
    //此处定义常量是便于理解
    const UP=38;
    const DOWN=40;
    const LEFT=37;
    const RIGHT=39;
    
    public function move($m){
        switch($m){
            case 37: echo "向左移动5px...<br/>"; break;
            case 38: echo "向上移动5px...<br/>"; break;
            case 39: echo "向右移动5px...<br/>"; break;
            case 40: echo "向下移动5px...<br/>"; break;
        }
    }
}

$g = new Game();
$g->move(Game::LEFT);
$g->move(Game::UP);
$g->move(Game::RIGHT);
$g->move(Game::DOWN);
$g->move(Game::UP);

 

很赞哦! (0)

文章评论

    高端网站建设