我有一个包含 send_notification 函数的 GCM
类。在另一个类 Demand.php
中,我尝试使用 send_notification 函数。所以我在 Demand.php
中有一个构造函数,它指向我的 GCM
类,如下所示:
$gcm = new GCM();
这个 $gcm
变量在该类内部的函数中使用,如下所示:
$result = $gcm->send_notification($registatoin_ids, $message);
这就是我得到错误的地方:
<br />n<b>Fatal error</b>: Call to a member function send_notification() on a non-object in..
我搜索了问题,发现问题是 $gcm
为 null,这就是它什么都不调用的原因。所以当我把
$gcm = new GCM();
在我的函数中它工作正常。但是没有其他方法可以做到这一点吗?我的意思是,只在 Demand.php
的构造函数中放入 creating $gcm
不就可以了吗?
以下是我所指的部分:
function __construct() {
require_once 'GCM.php';
require_once 'DB_Connect.php';
require_once 'DB_Functions.php';
// connecting to database
$this->db = new DB_Connect();
$this->db->connect();
$gcm = new GCM();
$df = new DB_Functions();
}
// destructor
function __destruct() {
}
public function getDistance($uuid, $name, $distance, $latstart, $lonstart, $latend, $lonend, $gcm_regId) {
$user_new = array ("$uuid", "$name", "$distance","$latstart", "$lonstart", "$latend", "$lonend","$gcm_regId");
$query = sprintf("SELECT uid, distance,latstart, lonstart, latend, lonend, gcm_regid, name FROM user_demand WHERE latstart='%s' AND lonstart='%s'",
mysql_real_escape_string($latstart),
mysql_real_escape_string($lonstart));
$user = mysql_query($query);
$no_of_rows = mysql_num_rows($user);
while($user_old = mysql_fetch_assoc($user))
{
$djson = $this->findDistance($latend,$lonend,$user_old["latend"],$user_old["lonend"] );
if ($user_old["distance"]+$distance>=$djson) {
$match = mysql_query("INSERT INTO matched_users(gcm_a, gcm_b, name_a, name_b) VALUES(".$user_old['gcm_regid'].",".$user_new['gcm_regId'].",".$user_old['name'].",".$user_new['name'].")");
$registatoin_ids = array($gcm_regId);
$message = array("var" => $name);
$result = $gcm->send_notification($registatoin_ids, $message);
}
}
}
最佳答案
如果将 $gcm = new GCM();
放在 Demand 类的构造函数中,则变量 $gcm
将仅在构造函数方法中可用。
如果您希望能够在整个 Demand 类中访问 $gcm
变量,您需要将其设置为类的属性,如下所示:
class Demand()
{
/**
* Declare the variable as a property of the class here
*/
public $gcm;
...
function __construct()
{
...
$this->gcm = new GCM();
...
}
function myFunction()
{
...
// You can access the GCM class now in any other method in Demand class like so:
$result = $this->gcm->send_notification($registatoin_ids, $message);
...
}
...
}
关于php - fatal error .. 调用成员函数.. 在非对象上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14242388/