首页 > 解决方案 > 未捕获的错误:调用成员函数

问题描述

我正在尝试在我的 php 文件中使用如下代码。

global $w;
func();
function func(){
$data = getAllNumbers();
$numbers = $data["data"];
$error = $data["error"];

for($i = 0; $i < count($numbers); $i++) {
    $w->sendPresenceSubscription($numbers[$i]);
}
}

在我的 whtaprot.class.php 中具有如下功能

 public function sendPresenceSubscription($to)
    {
        $node = new ProtocolNode('presence', ['type' => 'subscribe', 'to' => $this->getJID($to)], null, '');
        $this->sendNode($node);
    }

但我收到如下错误。我也无法修复它,也不知道它为什么会出现。如果我删除功能代码并直接使用它,它工作正常。

Uncaught Error: Call to a member function sendPresenceSubscription() on null in

索引.php

<?php
ini_set('memory_limit', '-1');
require_once('../src/whatsprot.class.php');
require_once('api.php');
require_once('storeStatus.php');


$starttime = time();

function onPresenceAvailable($mynumber, $from)
{
    storeStatus(explode("@", $from)[0], 1);
    echo "Online: ".$from."\n";
}

function onPresenceUnavailable($mynumber, $from)
{
    storeStatus(explode("@", $from)[0], 0);
    echo "Offline: ".$from."\n";
}


$debug = false;

$nickname = 'Test WA';
$username = '00000000';
$password = '00000000';


global $w;

$w = new WhatsProt($username, $nickname, $debug);

$w->eventManager()->bind('onPresenceAvailable', 'onPresenceAvailable');
$w->eventManager()->bind('onPresenceUnavailable', 'onPresenceUnavailable');


try {
  $w->connect();
} catch (Exception $e) {
  echo 'Connection error: ' . $e->getMessage();
  exit(0);
}

try {
  $w->loginWithPassword($password);
} catch (Exception $e) {
  echo 'Login error: ' . $e->getMessage();
  exit(0);
}
func();
function func(){
$data = getAllNumbers();
$numbers = $data["data"];
$error = $data["error"];

for($i = 0; $i < count($numbers); $i++) {
    $w->sendPresenceSubscription($numbers[$i]);
}
}

while (1) {
    try{
    $w->pollMessage();
    if(time()-$starttime > 14400) {
    break;
    }
    }
    catch (Exception $e) {
    }
 }

$w->disconnect(); 
?>

我在 index.php(51): func() 上遇到错误。谁能建议我这有什么问题?谢谢

标签: phphtmlmysql

解决方案


global $w在你的 func 函数中声明。

就像是:

function funct() {
    global $w;
    //the rest of codes here
}

推荐阅读