<?php
class controller
{
public function view()
{
echo "this is controller->view";
}
}
class home extends controller
{
public function index()
{
echo "this is home->index";
}
function page()
{
echo "this is home-> page";
}
}
$obj= new home;
$method="index";// set to view or page
if(method_exists($obj,$method))
{
$obj->{$method}();
}
?>
我的问题:
如果我们设置$ method来查看,将调用基类控制器类中的view()
我想检查$类仅存在于home类中
(不想检查函数是否在基类中定义)
任何想法如何被证明?
答案 0 :(得分:4)
将基类功能定义为私有。
更改
public function view()
{
echo "this is controller->view";
}
到
private function view()
{
echo "this is controller->view";
}
这将是有效的......
修改强>
function parent_method_exists($object,$method)
{
foreach(class_parents($object) as $parent)
{
if(method_exists($parent,$method))
{
return true;
}
}
return false;
}
if(!(method_exists($obj,$method) && parent_method_exists($obj,$method)))
{
$obj->{$method}();
}
这将完全适用于您的情况...
另请参阅this link
答案 1 :(得分:0)
根据@vignesh 的回答,我需要使用 is_callable()
使其工作。
abstract class controller {
private function view() {
echo "this is controller->view";
}
}
class home extends controller {
public function index() {
echo "this is home->index";
}
public function page() {
echo "this is home->page";
}
}
$home_controller = new home;
is_callable([ $home_controller, 'view']); // false