Jump to content

Calling a class method inside another class


play_

Recommended Posts

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")... ?
  }
}

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

 

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.

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.