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

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

const属性

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

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

实例代码如下:

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

提示:使用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);
?>


本文地址:

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

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

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

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function