我想从父类中定义的函数中调用子类中定义的函数以获取某些逻辑。我收到未定义函数的错误。如何调用此函数。这是我的示例代码。
<?php
class First
{
public function __construct()
{
echo "First class is initiated.";
}
public function call_child()
{
$this->get_ouput();
}
}
class Second extends First
{
public function __construct()
{
parent::__construct();
}
public function get_output()
{
echo "Here is your output";
}
}
$obj = new Second();
$obj->call_child();
?>
答案 0 :(得分:0)
调用get_output
方法时出现错字。但是,您应该将First
类和get_output
方法定义为抽象方法,以便被其他类扩展/实现:
abstract class First
{
public function __construct()
{
echo "First class is initiated.";
}
abstract public function get_output();
public function call_child()
{
$this->get_output();
}
}
class Second extends First
{
public function get_output()
{
echo "Here is your output";
}
}
$obj = new Second();
$obj->call_child();
注意:如果Second
类仅调用父构造函数,则可能无法定义该构造函数。
答案 1 :(得分:0)
问题是您的函数调用名称中的拼写错误
<?php
class First
{
public function __construct()
{
echo "First class is initiated.";
}
public function call_child()
{
$this->get_output(); //update the name here
}
}
class Second extends First
{
public function __construct()
{
parent::__construct();
}
public function get_output()
{
echo "Here is your output";
}
}
$obj = new Second();
$obj->call_child();
?>