我试图用PHP自学OOP。我有一个儿童班的错误,有人知道为什么我会收到这个错误吗?
致命错误:在第28行的C:\ wamp \ www \ starter \ display.php中调用未定义的方法User :: getSkipper()
User类是这样的:
<?php
class User
{
protected $_first_name;
protected $_last_name;
protected $_email;
public function __construct($first_name, $last_name, $email)
{
$this->_first_name = $first_name;
$this->_last_name = $last_name;
$this->_email = $email;
}
public function getFirstName()
{
return $this->_first_name;
}
public function getLastName()
{
return $this->_last_name;
}
public function getEmail()
{
return $this->_email;
}
}
?>
船长课是这样的:
<?php
class Skipper extends User
{
protected $_skipper;
public function __construct($first_name, $last_name, $email, $skipper)
{
$this->_skipper = $skipper;
}
public function getSkipper()
{
return $this->_skipper;
}
}
?>
执行以下代码时抛出错误:
$user1 = new User('Steven', 'Smith', 'steve@sljgksdj.com', 'Yes');
echo '<p>First Name: ' . $user1->getFirstName() .'</p>';
echo '<p>Last Name: ' . $user1->getLastName() .'</p>';
echo '<p>Email: ' . $user1->getEmail() .'</p>';
echo '<p>Skipper: ' . $user1->getSkipper() .'</p>';
答案 0 :(得分:0)
如果skipper扩展了User,则需要实例化Skipper。另外,我对于将“是”传递给Skipper构造函数时想要实现的目标感到困惑。
<?php
class User
{
protected $_first_name;
protected $_last_name;
protected $_email;
public function __construct($first_name, $last_name, $email)
{
$this->_first_name = $first_name;
$this->_last_name = $last_name;
$this->_email = $email;
}
public function getFirstName()
{
return $this->_first_name;
}
public function getLastName()
{
return $this->_last_name;
}
public function getEmail()
{
return $this->_email;
}
};
<?php
class Skipper extends User
{
protected $_skipper;
public function __construct($first_name, $last_name, $email, $skipper)
{
parent::__construct($first_name, $last_name, $email)
$this->_skipper = $skipper;
}
public function getSkipper()
{
return $this->_skipper;
}
}
$skipper1 = new Skipper('Steven', 'Smith', 'steve@sljgksdj.com', 'Yes');
echo '<p>First Name: ' . $skipper1->getFirstName() .'</p>';
echo '<p>Last Name: ' . $skipper1->getLastName() .'</p>';
echo '<p>Email: ' . $skipper1->getEmail() .'</p>';
答案 1 :(得分:0)
您创建了一个类user
的对象,而用户没有任何方法getSkipper
。
您应该创建类Skipper
的对象。
$user1 = new Skipper('Steven', 'Smith', 'steve@sljgksdj.com', 'Yes');