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