Home php教程 php手册 php类和对象之protected与const属性

php类和对象之protected与const属性

May 25, 2016 pm 04:47 PM
php class protected

本文章给大家介绍在php中类和对象的protected与const属性用法,有需要了解的朋友可参考参考.

const属性

用const属性定义的字段是一个常量,类中的常量和静态变量类似,不同之处就是常量的值一旦赋值不能被改变.const定义常量不需要加$符号,其结构形式如下:

const 常量名称  //常量名称不能用$符号

实例代码如下:

<?php
class Date {
    const M = "Monday";
}
echo "today is " . Date::M;
?>
Copy after login

提示:使用const定义的常量名称一般都大写,这是一个约定,我们要养成一个良好的命名方式习惯.如果定义的常量由多个单词组成,则使用下划线_链接,这也是一个约定.例如:FILE_SIZE.

protected属性

protected限定的字段作用域在public和private之间,若该成员被声明称protected(保护),则代表只能在该类和该类的子类中使用该字段.

实例代码如下:

<?php
class me {
    protected $Money = 100;
    protected $price1 = 60;
    public function Sell($price) {
        if ($this->price1 <= $price) {
            echo "好,卖给你了.
";
            $this->Money = $this->Money + $price;
            return "我现在总共有 " . $this->Money . " 元钱";
        } else {
            echo "我不卖 ,$price 太便宜了
";
            return "现在我还是 " . $this->Money . " 元钱";
        }
    }
}
$now = new me;
echo $now->Sell(30);
?>
Copy after login


本文地址:

转载随意,但请附上文章地址:-)

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)