2

I have an PDO object in an included file and when i use it in main page it works great. And when i pass it into an object to use it inside of them it simply dont work.

I've tried directly and with reference (function xxxx(&dbd){ this->$db = &dbd }), simply dont work, but if i pass another type of value (as a string) that works perfect. If i send a $db = "olaola" it works but if it is an PDO it fails. I'm a newbie in php and in english, so be patient please :P

included file:

$username = "root";
$password = "*****";
$host = "localhost";
$dbname = "dbname";
$db = NULL;
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');

try
{
    $db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
}
catch(PDOException $ex)
{
    die("Failed to connect to the database: " . $ex->getMessage());
}

$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

in main:

$pagMenu = new pages($db);

in pages class:

class pages {

    private $db;

    function __construct($db) { 
        $this->$db = $db;
    }
}
3
  • What does "doesn't work" mean exactly? What does or doesn't it do? Commented Nov 2, 2012 at 16:04
  • how do you access the $db object in your class pages? (you cant access it from outside because its private in your example) Commented Nov 2, 2012 at 16:05
  • Using $this->db in the pages class should have the same results as using $db in the main program. Commented Nov 2, 2012 at 17:31

3 Answers 3

6

The syntax is:

    $this->db = $db;

Not $this->$db.

Sign up to request clarification or add additional context in comments.

3 Comments

Well spotted. Do you know why it was working with the string?
Because a string resolves to a proper "variable variable", or rather "variable property" here. An object is not a valid variable name.
You should put that in the answer too.
5

You should do

$this->db = $db;

instead of

$this->$db = $db;

The second form is a variable variable, which means that you are assigning the value of the parameter to a variable named as the content of the variable, which will return an error if that content is a PDO object.

2 Comments

Tks a lot. By the way, do you know why i can use de db object in main but when i use it in "pages" class won't work? The fetchAll of resulting query in pages function return an array empty and in main result with the values.
Using the $db object in main should give the same results as using $this->db in the pages class, because they are the same thing. Not sure what the error could be.
0

Static syntax

$self::$variableName

This syntax

$this->variableName

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.