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

Link to comment
Share on other sites

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

 

Link to comment
Share on other sites

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.

?>

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.