Heim  >  Artikel  >  Backend-Entwicklung  >  php类和对象之protected与const属性_PHP教程

php类和对象之protected与const属性_PHP教程

WBOY
WBOYOriginal
2016-07-13 17:15:45910Durchsuche

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

const属性
用const属性定义的字段是一个常量,类中的常量和静态变量类似,不同之处就是常量的值一旦赋值不能被改变。

const定义常量不需要加$符号,其结构形式如下:

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

实例:

 代码如下 复制代码

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


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

protected属性

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

实例:

 代码如下 复制代码

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

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/628819.htmlTechArticle本文章给大家介绍在php中类和对象的protected与const属性用法,有需要了解的朋友可参考参考。 const属性 用const属性定义的字段是一个常量,类...
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn