Reputation: 1922
I am trying to use anonymous function in the constructor , to assign it to a public variable and then using that variable in methods.
My Class
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'"),
);
}
}
Call to Class
$siteAnalytics = new siteAnalytics($db_count, $db_sum, $db_readAll);
print_r($siteAnalytics->siteData());
What is the error?
Uncaught Error: Call to undefined method siteAnalytics::db_count()
I am getting the error, in the siteData()
method in the array where $this->db_count
is getting called !
I know i can pass anonymous functions through the methods but why it is not working while passing through the constructor.
Upvotes: 1
Views: 208
Reputation: 7428
You can try to assign a property to a local variable and then call it like a function:
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'"),
);
}
Update: You can try to surround your property retrieving with a pair of parentheses:
public function siteData(){
// CREATE "SITE DATA" ARRAY FROM QUERIES
$SD_array = array(
'U_active' => ($this->db_count)("users", "*", "WHERE a_status='true'"),
);
}
Upvotes: 2