如何知道在PHP中调用哪个类方法?
作为标题,如何知道在PHP中调用哪个类方法?,php,class,oop,Php,Class,Oop,作为标题,$a为a类,并调用foo函数 $a->foo(); 然而,类A有许多子类,子类。其中一些使用了几十种特性,实现了许多接口。我不确定是哪个子类$a。 我的问题是,我怎么知道调用了哪个foo函数?我肯定可以使用不正确的参数调用foo() $a->foo('error'); 我将得到错误跟踪堆栈。 但是如何直接获得类名或特征名呢? 提前谢谢 检查此示例: <?php class Foo { protected $who; public functio
$a
为a类,并调用foo函数
$a->foo();
然而,类A有许多子类,子类。其中一些使用了几十种特性,实现了许多接口。我不确定是哪个子类$a
。
我的问题是,我怎么知道调用了哪个foo函数?我肯定可以使用不正确的参数调用foo()
$a->foo('error');
我将得到错误跟踪堆栈。
但是如何直接获得类名或特征名呢?
提前谢谢 检查此示例:
<?php
class Foo
{
protected $who;
public function printItem($string)
{
echo 'printItem (' . __CLASS__ . '): ' . $string . PHP_EOL;
$this->who = __CLASS__;
}
public function getClass()
{
echo $this->who . PHP_EOL;
}
}
class Bar extends Foo
{
public function printItem($string)
{
echo 'printItem (' . __CLASS__ . '): ' . $string . PHP_EOL;
$this->who = __CLASS__;
}
}
$a = new Foo();
$b = new Bar();
$a->printItem('baz'); // Output: 'printItem (Foo): baz'
$a->getClass(); // Output: Foo
$b->printItem('baz'); // Output: 'printItem (Bar): baz'
$b->getClass(); // Output: Bar
?>
您可以在中阅读更多内容:
这是演示,试试这个
谢谢你的评论。但它无法判断调用了哪个printItem()。它只是打印当前的类名。printItem可以从它的任何超类中获得。@WikiOops,如果您看到$a->printItem('baz');输出为“printItem(Foo):baz”是来自Foo的printItem,它被调用。这不是你想要的吗?@WikiOops你有进步吗?这可能不是我想要的。
Here is the demo ,try this
<?php
class myclass {
function myclass() {
return(true);
}
function myfunc1(){
return(true);
}
function myfunc2(){
return(true);
}
}
$class_methods = get_class_methods('myclass');
// or
$class_methods = get_class_methods(new myclass());
foreach ($class_methods as $method_name) {
echo "$method_name\n";
}
// output :myclass myfunc1 myfunc2