play_ Posted February 27, 2007 Share Posted February 27, 2007 How can it be done? say i have class SQL { function query($query) { $this->result = @mysql_query($query, $this->linkid); if(! $this->result) { echo '<br />Query failed'; } $this->querycount++; return $this->result; } } class B { function hello() { // need to use function 'query' here. // Do i create an instance of SQL in here and use it like $sql->query("select * from users")... ? } } Quote Link to comment Share on other sites More sharing options...
btherl Posted February 27, 2007 Share Posted February 27, 2007 For that example, yes you must create an instance of SQL, because the method refers to $this. But in general, you can just use SQL::query($var); Quote Link to comment Share on other sites More sharing options...
play_ Posted February 27, 2007 Author Share Posted February 27, 2007 Yes, i can. Wasn't working at first, but now it is. class player { function retrieveStats($userID) { $sql = new mysql(); $sql->query("SELECT * FROM user_character WHERE userID = '$userID'"); $this->result = $sql->fetchArray(); return $this->result; } } class mysql { function query($query) { $this->result = @mysql_query($query, $this->linkid); if(! $this->result) { echo '<br />Query failed'; } $this->querycount++; return $this->result; } } Use it like this: $player = new player(); $row = $player->retrieveStats('1'); // outputs 1. 1 was the playerID sent as paremeter Quote Link to comment Share on other sites More sharing options...
play_ Posted February 27, 2007 Author Share Posted February 27, 2007 For that example, yes you must create an instance of SQL, because the method refers to $this. But in general, you can just use SQL::query($var); never came upon :: before so i'll stick to what i just did. =] Thanks though. Quote Link to comment Share on other sites More sharing options...
play_ Posted February 27, 2007 Author Share Posted February 27, 2007 Howcome i can't initiate an instance of mysql class in the __construct() method? function __construct() { $sql = new mysql(); } gives: Notice: Undefined variable: sql in local/path on line 209 Quote Link to comment Share on other sites More sharing options...
Jenk Posted February 27, 2007 Share Posted February 27, 2007 The double colon is a static operator, you cannot use it to call an instantiated object, it will call the method of the class as if it were just a function. Learn to pass the objects around, in true to OOP. <?php $mysql = new SQL; $B = new B($mysql); // pass the $mysql object to $B so it can store it within it's properties and utilise it. ?> Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.