in oop neither boom boom, trying to understand why the following error is issued:

Notice: Undefined variable: pdo in C:\MAMP\htdocs\PolitHouse\model\userinfo.php on line 10 Fatal error: Uncaught Error: Call to a member function prepare() on null in C:\MAMP\htdocs\PolitHouse\model\userinfo.php:10 Stack trace: #0 C:\MAMP\htdocs\PolitHouse\model\userinfo.php(21): User->userPview() #1 {main} thrown in C:\MAMP\htdocs\PolitHouse\model\userinfo.php on line 10 

Before that I have never used any classes or functions, trying to figure out how it works. The code itself is here:

 <?php include_once('../controller/db.php'); class User { public $uid = 1; public function userPview() { $query = ('SELECT politview FROM users WHERE id = :id'); $stmt = $pdo->prepare($query); $stmt->execute(['id' => $uid]); $results = $stmt->fetch(PDO::FETCH_ASSOC); echo $results; } } $user = new User(); echo $user->uid; $user->userPview(); ?> 

    1 answer 1

    $pdo variable out of scope

    In programming, scope (English scope) denotes a program area within which an identifier (name) of a variable continues to be associated with this variable and return its value. Outside scope, the same identifier can be associated with another variable, or be free (not associated with any of them).

    Get acquainted with the fact that such a scope and what they are in PHP can be here .

    To solve your problem, pass the variable to the class constructor:

     <?php include_once '../controller/db.php'; class User { protected $uid = 0, $pdo = null; public function __construct(int $uid, $pdo) { $this->uid = $uid; $this->pdo = $pdo; } public function getId() : int { return $this->uid; } public function userPview() { $query = 'SELECT `politview` FROM `users` WHERE `id` = :id'; $stmt = $pdo->prepare($query); $stmt->execute(['id' => $this->uid]); $results = $stmt->fetch(PDO::FETCH_ASSOC); return $results; } } $user = new User(1, $pdo); echo 'User ID: ', $user->getId(), PHP_EOL; print_r($user->userPview()); 

    Attention! Sample code supported by PHP version 7+