找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 1090|回复: 0

魔术方法

[复制链接]

304

主题

42

回帖

1338

积分

管理员

积分
1338
发表于 2021-4-22 12:19:10 | 显示全部楼层 |阅读模式
认识魔术方法
  1. <?php

  2. // 封装
  3. // 魔术方法: 满足特定条件时,自动调用
  4. // 当用户在外部动态创建属性的时候,魔术方法 __set() 也会自动调用

  5. class Girl
  6. {
  7.         // 私有属性

  8.         private $name;
  9.         private $weight;

  10.         public function __construct($name, $weight)
  11.         {
  12.                 $this->name = $name;
  13.                 $this->weight = $weight;
  14.         }

  15.         // 魔术方法:读取不可访问的属性时,自动调用。
  16.         public function __get($key)
  17.         {
  18.                 // echo $this->$key; // $this->weight;
  19.                 return $this->$key;
  20.         }

  21.         public function __set($key, $value)
  22.         {
  23.                 var_dump($key, $value);
  24.                 // $key = height, $value = 123

  25.                 // $this->height = 123
  26.                 $this->$key = $value;
  27.         }

  28. }

  29. $coco = new Girl('coco', 200);

  30. $coco->height = 123;

  31. echo $coco->weight;
  32. echo '<pre>';
  33.         print_r($coco);
  34. echo '</pre>';
复制代码
了解魔术方法
  1. <?php

  2. // 封装

  3. // 当我们需要动态创建类的属性和方法是,我们是可以通过魔术方法来实现的。

  4. // 当访问没有定义或者不可见的属性和方法时,魔术方法会被调用。

  5. class Girl
  6. {
  7.         private $name;
  8.         private $weight;

  9.         public function __construct($name, $weight)
  10.         {
  11.                 $this->name = $name;
  12.                 $this->weight = $weight;
  13.         }

  14.         public function __get($key)
  15.         {
  16.                 return $this->$key;
  17.         }

  18.         public function __set($key, $value)
  19.         {
  20.                 var_dump('run:set', $key, $value);
  21.                 $this->$key = $value;
  22.         }

  23. }

  24. $lili = new Girl('lili', 180);
  25. echo '<pre>';
  26.         print_r($lili);
  27. echo '</pre>';
  28. // 访问私有属性
  29. echo $lili->weight;

  30. // 设置私有属性
  31. $lili->weight = 190;

  32. // 动态添加一个未定义的属性
  33. $lili->age = 18;
复制代码


回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|小黑屋|外汇论坛 ( 粤ICP备16021788号 )

GMT+8, 2024-10-23 07:21 , Processed in 0.072433 second(s), 19 queries .

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表