类的类型提示 - 将类名放在需要约束的方法参数之前

语法格式:

public function write(ShopProduct $shopProduct){}

数组提示:

public function setArray(array $storearray){}

class ShopProduct{
public $title = 'default product'; // 属性也称为成员变量,用来存放对象之间互不相同的数据
public $producerMainName = 'main name';
public $producerFirstName = 'first name';
public $price = 0; // 创建对象时,构造方法会被自动调用,构造方法可以确保必要的属性设置,并完成任何需要准备的工作
public function __construct($title,$producerMainName,$producerFirstName,$price){
$this->title = $title; // 使用伪变量$this给每个变量赋值
$this->producerMainName = $producerMainName;
$this->producerFirstName = $producerFirstName;
$this->price = $price;
} public function getProducer(){ // 方法让对象执行任务
return $this->producerMainName . $this->producerFirstName;
}
} class ShopProductWriter{
public function write(ShopProduct $shopProduct){ // 类的类型提示,只需将类名放在需要约束的方法参数之前
$str = $shopProduct->title . ':' . $shopProduct->getProducer() . "($shopProduct->price) . </br>";
print $str;
} public function setArray(array $storearray){ // 数组提示
var_dump($storearray);
} public function setWriter(ObjectWriter $objectWriter=null){
var_dump($objectWriter);
}
} class Wrong{};
$store = array('name'=>'taobao');
$objectWriter = NULL; $product1 = new ShopProduct('My Antonia','Willa','Cather',5.99); // 更易于实例化,也更安全,实例化和设置只需要一条语句就可以完成,任何使用ShopProduct对象的代码都可以相信所有的属性皆被初始化了
$writer = new ShopProductWriter();
$writer->write($product1); // 有了参数提示,规定此处只能传入new ShopProduct对象
$writer->write(new Wrong()); // 传入其它的对象会出现:Catchable fatal error: Argument 1 passed to ShopProductWriter::write() must be an instance of ShopProduct, instance of Wrong given..从而防止隐藏bug的产生。
$writer->setArray($store); // 有了参数提示,规定此处只能传入一个数组
$writer->setWriter($objectWriter); // 有了参数提示,规定此处只能传入NULL

最新文章

  1. Ubuntu16.04下安装VS Code
  2. Ajax技术原理小结
  3. Azure Redis Cache (1) 入门
  4. 简直要逆天!超炫的 HTML5 粒子效果进度条
  5. EventBus初理解
  6. mybatis 插入日期类型精确到秒的有关问题
  7. [Redux] Extracting Action Creators
  8. RadioButton、CheckBox与ToggleButton
  9. levelDB跳表实现
  10. Struts2第一个工程helloStruts极其基本配置
  11. setTimeout与setInterval的区别
  12. 剑指offer之有序二维数组查找
  13. 将SpringMVC中的HttpMessageConverter替换为Gson
  14. 201521123048 《Java程序设计》第12周学习总结
  15. C++11智能指针的深度理解
  16. 全网最详细的一款满足多台电脑共用一个鼠标和键盘的工具Synergy(图文详解)
  17. 宿主机系统 Deepin 15.4,解决 Virtualbox 5.1 中 XP虚拟机无法使用 USB设备(如:U盘、罗技优联接收器等)的问题
  18. rpm 包的安装、卸载、升级、查询、验证
  19. Android学习之基础知识四-Activity活动7讲(活动的启动模式)
  20. 002-linux使用SecureCRT

热门文章

  1. C#使用RabbitMQ
  2. openstack 安全策略权限控制等api接口
  3. adb启动和停止android app方法
  4. 安装cactiez v11对windows和linux系统进行监控
  5. centos系统中perl进程病毒占用大量网络流量导致网络瘫痪的问题分析及解决方案
  6. sklearn,交叉验证中的分层抽样
  7. C++ code:More Loop Designs
  8. Iterator 接口
  9. (七)dubbo服务集群实现负载均衡
  10. 性能测试二十六:环境部署之Mysql+Redis+Tomcat环境整合