【问题标题】:PHP: how do you get the method called from the constructor?PHP:你如何获得从构造函数调用的方法?
【发布时间】:2013-10-22 18:36:38
【问题描述】:

PHP 有 get_call_class();这将返回所调用的类的名称。是否有返回被调用方法名称的函数?例如,我有一个父类:

class Parent
{
    public function __construct()
    {
        echo get_called_class(); // echos "Child"
        // how do I echo "myMethod"
    }
}

然后我有一个孩子父母:

class Child extends Parent
{
    public function myMethod()
    {
    }
}

如果我打电话:

new Parent();

如何获取从 __construct 调用的方法的名称 - 在本例中为“myMethod”?如果我使用__FUNCTION__,它会返回Parent::__construct

编辑:我试图让被调用的类和方法自动传递给视图函数。所以在我的控制器动作中,我可以拥有:

$this->render();

代替:

$this->render('account/new');

我的 __construct 会自动设置

$controller = "account"; // from get_called_class();
$action = "new"; // gotten how?!

【问题讨论】:

  • 你为什么要这样做?
  • 为什么需要这个?它暗示了一种设计气味
  • 创建对象时,__construct 被调用...
  • 您的代码实际上并没有调用 myMethod...
  • 我感觉你试图以错误的方式解决这个问题,但这个想法是有效的。我会做的是让视图查询类似于请求,以便它可以尝试确定模板。你的请求对象应该有一个控制器和一个它想要调用的方法,所以你的视图对象也应该查看请求以收集它自己的信息。

标签: php class methods


【解决方案1】:

获取格式为“filename: [class->][function(): ]”的字符串的简单函数

<?php
function get_caller_info() {
    $c = '';
    $file = '';
    $func = '';
    $class = '';
    $trace = debug_backtrace();
    if (isset($trace[2])) {
        $file = $trace[1]['file'];
        $func = $trace[2]['function'];
        if ((substr($func, 0, 7) == 'include') || (substr($func, 0, 7) == 'require')) {
            $func = '';
        }
    } else if (isset($trace[1])) {
        $file = $trace[1]['file'];
        $func = '';
    }
    if (isset($trace[3]['class'])) {
        $class = $trace[3]['class'];
        $func = $trace[3]['function'];
        $file = $trace[2]['file'];
    } else if (isset($trace[2]['class'])) {
        $class = $trace[2]['class'];
        $func = $trace[2]['function'];
        $file = $trace[1]['file'];
    }
    if ($file != '') $file = basename($file);
    $c = $file . ": ";
    $c .= ($class != '') ? ":" . $class . "->" : "";
    $c .= ($func != '') ? $func . "(): " : "";
    return($c);
}
?>

用法如下:

<?php
function debug($str) {
    echo get_caller_info() . $str . "<br>\n";
}
?>

取自PHP Manual,这是我最好的朋友。

【讨论】:

  • 我希望不使用 debug_backtrace,但这似乎是唯一的方法。
【解决方案2】:

我认为你可以使用__METHOD__

http://php.net/manual/en/language.constants.predefined.php

否则正如其他人所说,它应该返回 __construct。

【讨论】:

【解决方案3】:

正如 DCoder 所写,您根本不会调用 myMethod()。 您构造的是 Parent 类对象,而不是 Child 类对象,因此不可能以任何方式从 Yout 子类中获取任何函数名称或任何东西。

【讨论】:

    猜你喜欢
    • 2012-06-11
    • 2015-10-01
    • 2013-08-10
    • 2015-05-17
    • 1970-01-01
    • 1970-01-01
    • 2016-05-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多