我有一个名为Media的类,以及两个名为Sms和Mail的类。两者都扩展了媒体类。
<?php
class Media {
protected $receiver;
protected $type;
public function __construct($receiver, $type)
{
$this->setReceiver($receiver);
$this->type($type);
}
public function getReceiver()
{
return $this->receiver;
}
public function setReceiver($receiver)
{
if($this->getType() == 'SMS' && !is_int($receiver)){
//return exception if type is SMS and receiver not a number
}
$this->receiver = $receiver;
return $this;
}
public function getType()
{
return $this->type;
}
public function setType($type)
{
$this->type = $type;
return $this;
}
}
class Sms extends Media {
}
$sms = new Sms('0123456789', 'SMS');
结果是此错误:
致命错误:未捕获的错误:调用未定义的方法Sms :: type()
我无法访问type
。
我想用setter方法在类型为SMS时检查接收者是否为数字。
我们可以想象另一类扩展媒体的邮件,我想验证接收者是否是邮件而不是数字。
我应该在哪里进行检查?
这里您正尝试使用字段作为方法:
$this->type($type);
相反,使用其设置器setType
:
public function __construct($receiver, $type)
{
$this->setReceiver($receiver);
$this->setType($type);
}