Thursday, 15 July 2010

php - Call to a member function query on a non-object -



php - Call to a member function query on a non-object -

i receive fatal error when working objects in php:

call fellow member function query() on non-object

index.php:

$db = new pdo("mysql:host=localhost;dbname=world;charset=utf8", "root", "xxx"); $db->setattribute(pdo::attr_errmode, pdo::errmode_exception); $conn = new connection($db); $data = $conn->getcities(); foreach ($data $row) { print_r($row); }

connection.php:

class connection { protected $db; public function _construct(pdo $db) { $this->db = $db; } public function getcities() { homecoming $this->db->query("select * city"); \\ error here } }

in single file works fine:

$db = new pdo("mysql:host=localhost;dbname=world;charset=utf8", "root", "xxx"); $db->setattribute(pdo::attr_errmode, pdo::errmode_exception); $data = $db->query("select * city"); foreach($data $row) { print_r($row); }

what object orientation i'm not understanding, or there reason?

if code snippet copy/paste , accurate, may have simple typo in constructor. in php, must start 2 underscores in row, , code has one:

class connection { public function _construct(pdo $db) { $this->db = $db; } }

should become

class connection { public function __construct(pdo $db) { $this->db = $db; } }

the explanation this: existing code contains no syntactical or semantic errors. there method called _construct never gets called. when create new object, is constructing object, passing in never-used $db gets silently ignored.

php

No comments:

Post a Comment