加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 致命错误..在非对象上调用成员函数..

发布时间:2020-12-13 22:04:53 所属栏目:PHP教程 来源:网络整理
导读:我有一个包含send_notification函数的GCM类.在另一个类Demand.php中,我试图使用send_notification函数.所以我在Demand.php中有一个构造函数,它指向我的GCM类,如下所示: $gcm = new GCM(); 这个$gcm变量用在该类中的函数中,如下所示: $result = $gcm-send_n
我有一个包含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的构造函数中创建$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,$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);
        ...
    }
    ...
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读