在类构造函数中使用匿名函数并在in方法中使用

时间:2019-04-09 20:28:52

标签: php class methods constructor

我试图在构造函数中使用匿名函数,将其分配给公共变量,然后在方法中使用该变量。

我的班级

class siteAnalytics {
    public $db_count;                                           // FUNCTION "$db_count" - CALLED FROM "FUNCTIONS.PHP"
    public $db_sum;                                             // FUNCTION "$db_sum" - CALLED FROM "FUNCTIONS.PHP"
    public $db_readAll;                                         // FUNCTION "$db_readAll" - CALLED FROM "FUNCTIONS.PHP"

    public function __construct($db_count, $db_sum, $db_readAll) {
        $this->db_count   = $db_count;
        $this->db_sum     = $db_sum;
        $this->db_readAll = $db_readAll;
    }

    public function siteData(){
        // CREATE "SITE DATA" ARRAY FROM QUERIES
        $SD_array = array(
            'U_active'       => $this->db_count("users", "*", "WHERE a_status='true'"),
        );
    }
}

召集课堂

$siteAnalytics = new siteAnalytics($db_count, $db_sum, $db_readAll);
print_r($siteAnalytics->siteData());

怎么了?

  

未捕获的错误:调用未定义的方法siteAnalytics :: db_count()

我在调用siteData()的数组中的$this->db_count方法中收到错误!

我知道我可以通过方法传递匿名函数,但是为什么在通过构造函数时匿名函数不起作用。

1 个答案:

答案 0 :(得分:2)

您可以尝试将属性分配给局部变量,然后像调用函数一样调用它:

public function siteData(){
    $db_count = $this->db_count;
    // CREATE "SITE DATA" ARRAY FROM QUERIES
    $SD_array = array(
        'U_active'       => $db_count("users", "*", "WHERE a_status='true'"),
    );
}

更新: 您可以尝试使用一对括号将检索到的属性括起来:

public function siteData(){
    // CREATE "SITE DATA" ARRAY FROM QUERIES
    $SD_array = array(
        'U_active'       => ($this->db_count)("users", "*", "WHERE a_status='true'"),
    );
}