php 对象直接访问私有属性
Jun 23, 2016 pm 01:24 PM
<?php header("content-type:text/html;charset=UTF-8"); class Person{ //私有的成员属性,对直接访问象 private $name; private $age; private $sex; //魔术方法 __construct(), __set(), __unset(), __isset(), __unset()..... function __construct($name="name1",$age =20,$sex="女"){ $this->name=$name; $this->age=$age; $this->sex=$sex; } /* 输出 Cannot access private property Person::$name 对象不能直接访问和设置私有属性的值,但是通过魔术方法__get($proName), __set($proName,$proValue)可以做到. 步骤: 1.重写魔术方法__get($property) , __set($proName,$proValue) 2.用对象直接访问或设置私有属性 $p1->name="对象直接访问私有属性"; echo $p1->name; 3.对象直接访问或设置私有属性时,会自动调用魔法方法__get($proName), __set($proName,$proValue) */ function __get($proName){ return $this->$proName; } function __set($proName,$proValue){ $this->$proName=$proValue; } function say(){ echo "$this->name:我的年龄$this->age,性别:$this->sex<br>"; } function run(){ $this->left(); $this->right(); } private function left(){ echo "left"; } private function right(){ echo "right"; } //析构方法,对象销毁前自动调用 function __destruct(){ echo "$this->name:我走了<br>"; } } $p1 = new Person("name1",15,"女"); $p2 = new Person("name2",20,"男"); $p3 = new Person("name3",30,"女"); /* 对象直接访问或设置私有属性 */ $p1->name="对象直接访问私有属性"; echo $p1->name."<br>"; /* 输出,注意__destruct()的输出顺序 name1:我的年龄15,性别:女 name2:我的年龄20,性别:男 name3:我的年龄30,性别:女 name1:我走了 name3:我走了 name2:我走了 */ $p1->say(); $p2->say(); $p3->say(); $p1=null; ?>
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 Article
Repo: How To Revive Teammates
3 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌
How Long Does It Take To Beat Split Fiction?
3 weeks ago
By DDD
R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌

Hot tools Tags

Hot Article
Repo: How To Revive Teammates
3 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌
How Long Does It Take To Beat Split Fiction?
3 weeks ago
By DDD
R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

11 Best PHP URL Shortener Scripts (Free and Premium)

Working with Flash Session Data in Laravel

Build a React App With a Laravel Back End: Part 2, React

Simplified HTTP Response Mocking in Laravel Tests

cURL in PHP: How to Use the PHP cURL Extension in REST APIs

12 Best PHP Chat Scripts on CodeCanyon
