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

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了php – 致命错误..在非对象上调用成员函数..脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个包含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);
        ...
    }
    ...
}
@H_502_53@

脚本宝典总结

以上是脚本宝典为你收集整理的php – 致命错误..在非对象上调用成员函数..全部内容,希望文章能够帮你解决php – 致命错误..在非对象上调用成员函数..所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。