我只想访问类
中声明的函数中的特定值class Animal
{
var $name;
function __Construct($names){
$this->name=$names;
}
}
class Dog extends Animal
{
function prop($ht, $wt, $ja)
{
$height=$ht;
$weight=$wt;
$jaw=$ja;
}
}
$dog= new dog('Pug');
$dog->prop(70, 50, 60);
我想仅回显dog
函数prop
中的特定值。
类似于dog->prop->jaw;
这是怎么做到的?
答案 0 :(得分:2)
听起来你想要这样的东西......
class Dog extends Animal {
private $props = array();
public function prop($height, $width, $jaw) {
$this->props = array(
'height' => $height,
'width' => $width,
'jaw' => $jaw
);
return $this; // for a fluent interface
}
public function __get($name) {
if (array_key_exists($name, $this->props)) {
return $this->props[$name];
}
return null; // or throw an exception, whatever
}
}
然后你可以执行
echo $dog->prop(70, 50, 60)->jaw;
或单独
$dog->prop(70, 50, 60);
echo $dog->jaw;