dounao2829 2014-10-27 19:49
浏览 27
已采纳

PHP - 在类中使用全局变量(致命错误)[关闭]

I have a class.php file, in which I include a class from another file:

class.php:

 include($_SERVER['DOCUMENT_ROOT'] . "/includes/user.php");
 $user = new User;     

So, inside /includes/user.php is the $user class defined.

And in /includes/user.php there is a function named getSocialUser($username);:

function getSocialUser ($username)
{
    global $dbh;
    $stmt = $dbh->prepare("SELECT * FROM users WHERE username=:username");
    $stmt->bindParam(':username', $username);
    $stmt->execute();

    $udata = $stmt->fetch();

    if(count($udata) == 0)
        return false;

    return $udata;
}

(The $dbh holds the database value. I've tested it, and it does have a connection to the database)

However, I want to be able to use that function above inside the class.php file:

This is what I am doing now:

class.php:

 include($_SERVER['DOCUMENT_ROOT'] . "/includes/user.php");
 $user = new User;  


 Class feed {

   function randomFunction($username) {
   global $user;
   $username = "test";
   $viewuser = $user->getSocialUser($username);

   echo $viewuser['avatar'];
  }
}

The above code doesn't work. I get this error:

Fatal error: Call to a member function getSocialUser() on a non-object in/path/class.php on line 6

What am I doing wrong?

  • 写回答

2条回答 默认 最新

  • duanche8554 2014-10-27 19:59
    关注

    To start off, using GLOBAL is bad practice. Instead, add the database connection as a parameter, so change your function to the following

    function getSocialUser ($dbh, $username)
    {
        $stmt = $dbh->prepare("SELECT * FROM users WHERE username=:username");
        $stmt->bindParam(':username', $username);
        $stmt->execute();
    
        $udata = $stmt->fetch();
    
        if(count($udata) == 0)
            return false;
    
        return $udata;
    }
    

    Next, initiate the database connection and the user class in a construct of your class,

     Class feed {
         private $dbh;
         private $user;
    
         function __construct() {
             $this->dbh = new PDO('your data here');
             $this->user = new User();
         }
    
         function randomFunction($username) {
             $username = "test";
             $viewuser = $this->user->getSocialUser($this->dbh,$username);
             echo $viewuser['avatar'];
         }
     }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器