blmg2009 Posted October 3, 2014 Share Posted October 3, 2014 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 https://forums.phpfreaks.com/topic/291407-php-classes/ Share on other sites More sharing options...
trq Posted October 3, 2014 Share Posted October 3, 2014 Quote 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 https://forums.phpfreaks.com/topic/291407-php-classes/#findComment-1492592 Share on other sites More sharing options...
blmg2009 Posted October 3, 2014 Author Share Posted October 3, 2014 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 https://forums.phpfreaks.com/topic/291407-php-classes/#findComment-1492594 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.