Home  >  Article  >  Backend Development  >  Protected and const attributes of PHP classes and objects_PHP tutorial

Protected and const attributes of PHP classes and objects_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 17:15:45912browse

This article will introduce you to the usage of protected and const attributes of classes and objects in PHP. Friends who need to know more can refer to it.

const attribute
A field defined with the const attribute is a constant. Constants in a class are similar to static variables. The difference is that the value of a constant cannot be changed once assigned.

Const definition constant does not need to add the $ symbol, its structure is as follows:

const constant name //Constant names cannot use the $ symbol

Example:

Tip: Constant names defined using const are generally capitalized. This is a convention. We must develop a good naming habit. It is also a convention to use underscore_links if the defined constant consists of more than one word. For example: FILE_SIZE.
The code is as follows
 代码如下 复制代码

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

Copy code


class Date{ const M="Monday"; }

echo "today is ".Date::M;

?>

 代码如下 复制代码

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);         
?>

protected attribute

The scope of the protected field is between public and private. If the member is declared protected, it means that the field can only be used in this class and subclasses of this class. Example:
The code is as follows Copy code
class me{                                         protected $Money =100; protected $price1=60;  public function Sell($price){ 

if($this->price1<=$price){  echo "Okay, I'll sell it to you.
";
$this->Money = $this->Money+$price;
Return "I now have a total of ".$this->Money." yuan"; } else{                                               echo "I don't want to sell it, $price is too cheap
"; return "Now I am still ".$this->Money." yuan"; } } } $now=new me;  echo $now->Sell(30); ?> http://www.bkjia.com/PHPjc/628819.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/628819.htmlTechArticleThis article introduces the usage of protected and const attributes of classes and objects in php. Friends who need to know more can Reference Reference. const attribute A field defined with a const attribute is a constant, class...
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