function - PHP - Using a global variable inside a class (Fatal Error) -



function - PHP - Using a global variable inside a class (Fatal Error) -

i have class.php file, in include class file:

class.php:

include($_server['document_root'] . "/includes/user.php"); $user = new user;

so, within /includes/user.php $user class defined.

and in /includes/user.php there function named getsocialuser($username);:

function getsocialuser ($username) { global $dbh; $stmt = $dbh->prepare("select * users username=:username"); $stmt->bindparam(':username', $username); $stmt->execute(); $udata = $stmt->fetch(); if(count($udata) == 0) homecoming false; homecoming $udata; }

(the $dbh holds database value. i've tested it, , have connection database)

however, want able utilize function above within class.php file:

this 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. error:

fatal error: phone call fellow member function getsocialuser() on non-object in/path/class.php on line 6

what doing wrong?

to start off, using global bad practice. instead, add together database connection parameter, alter function following

function getsocialuser ($dbh, $username) { $stmt = $dbh->prepare("select * users username=:username"); $stmt->bindparam(':username', $username); $stmt->execute(); $udata = $stmt->fetch(); if(count($udata) == 0) homecoming false; homecoming $udata; }

next, initiate database connection , user class in build of class,

class feed { private $dbh; private $user; function __construct() { $this->dbh = new pdo('your info here'); $this->user = new user(); } function randomfunction($username) { $username = "test"; $viewuser = $this->user->getsocialuser($this->dbh,$username); echo $viewuser['avatar']; } }

php function pdo

Comments

Popular posts from this blog

formatting - SAS SQL Datepart function returning odd values -

c++ - Apple Mach-O Linker Error(Duplicate Symbols For Architecture armv7) -

php - Yii 2: Unable to find a class into the extension 'yii2-admin' -