PHP之类型约束

PHP是弱类型,其特点是无需为变量指定类型,而且在其后也可以存储任何类型,不过在php的新语法中,在某些特定场合,针对某些特定类型,也可进行语法约束。

  • 特定场合:函数(方法)的形参变量
  • 特定类型:对象类型(类名)、接口类型(接口名)、数组类型(array)、函数类型(callable)

 

function f(类名 $p){} // 要求参数只能使用该类的对象

function f(接口名 $p){} // 要求该参数只能使用实现该接口的对象

function f(arrary $p){} // 要求该参数只能使用数组

function f(callable $p) // 要求该参数只能是一个函数(方法),此时称之为回调函数(方法)

 

eg:

<?php

header("Content-Type: text/html; charset=utf-8");

class Student {
private $_belong_teacher;
public function setTeacher(Teacher $t) {//要求参数只能使用该类的对象
$this->_belong_teacher = $t;
}
/**
* [__call description]
* @param string $m_name 重载方法名
* @param array $m_args 重载时所用的实参列表
* @return [type] [description]
*/
public function __call($m_name, $m_args) {
if (method_exists($this->_belong_teacher, $m_name)) {
return $this->_belong_teacher->$m_name();// 可变方法
} else {
trigger_error('老师都不知道');
}
}
}
class Teacher {
public function getAddress() {
return '北京天安门';
}
}
$t = new Teacher();
$s = new Student();
$s->setTeacher($t);// 建立的学生和老师的关联

// 通过学生获得地址
echo $s->getAddress();

posted @ 2017-03-09 18:47  Hmetoer  阅读(1380)  评论(1编辑  收藏  举报