Home> headlines> body text

PHP class attributes and class constants

无忌哥哥
Release: 2018-06-28 14:31:21
Original
3444 people have browsed it

*Class attributes and class constants

* 1. Class attributes only allow the following types of data to be initialized

* Scalar and array literals: strings, values, constants, arrays , Prototype document (php5.3)

* 2. Not allowed to use: variables, expressions, objects

* 3. Class constants are declared using the keyword const, and access restrictions are not allowed to be set , forced to be public and cannot be changed

* 4. Class constants are attribute classes and do not attribute to one of its instance objects. They must be accessed using classes

* 5. Access class constants To use the range parsing character::, double colon

* Use the keyword self in the class to indicate the current class, and the class name can be used directly externally

define('SITE_NAME','PHP中文网'); class User1 { //声明属性 private $siteName = SITE_NAME; private $name = '老顽童'; private $email = 'lwt@php.cn'; private $course = ['php','java','python']; const LECTURE = '朱老师'; //构造方法 public function __construct($name='',$email='', $siteName='',array $course=[]) { //如果传参,则使用新值初始化属性,否则使用默认值 $name ? ($this->name = $name) : $this->name; $email ? ($this->email = $email) : $this->email; $siteName ? ($this->siteName = $siteName) : $this->siteName; $course ? ($this->course = $course) : $this->course; } //查询器 public function __get($name) { return $this->$name; } //设置器 public function __set($name,$value) { return $this->$name = $value; } //在类中访问类常量,使用self来引用当前类名 public function getConst() { //类内部也可以直接使用当前类名 // return User1::LECTURE; //推荐使用self:当类名改变时,不必修改内部对它的引用 return self::LECTURE; } }
Copy after login


Related labels:
source:php.cn
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!