Jump to content

PHP Classes


blmg2009
Go to solution Solved by trq,

Recommended Posts

Hi there, 

 

This might a newbie question but I need help understanding PHP classes which am currently learning. 

 

I have an index page. 

 

With this three included files. 

 

database.php

config.php

account.php 

 

on database.php, the class is declared using $connection new Database(...), on this page is also all the coding for this class.

 

In config.php is a declared class of $account new Account($user_id);

 

and on account.php is all the details for the account class. 

 

on the index.php is echo $account->sayHello; 

 

However, My page is throwing out an error because I'm trying to use $connection->query(..) in my account.php / Account class. 

 

I have tried to extend the Account class with Database but still have no luck. 

 

How can I make sure the I can use a class function from another page in my Account class? 

 

 

 

Thanks for reading

Link to comment
Share on other sites

  • Solution

How can I make sure the I can use a class function from another page in my Account class?

You need to pass your $connection instance into your Account class via the __construct and store it on a property.

 

class Account
{
    protected $db;

    public function __construct(Database $db)
    {
        $this->db = $db;
    }
}
You can now use your Database object within your Account object by referencing $this->db.
Link to comment
Share on other sites

Brilliant, thank you very much; 

 

Works a treat. 

 

I also passed $user_id, which has allowed me to still pass over my user session id.

 

 

 
public function __construct(Database $db, $user_id)
{
$this->db = $db;
$this->user_id = $user_id;
}
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.