dnavarro
dnavarro

Reputation: 23

How to access a class object from an other class

My question is if i can access a class object from another class without the second one being extending the first one:

<?php 
class MySQL {
    public function query($data){
        //do something
    }
?>
<?php 
class Users {
    public function getUser($id){
        MySQL::query($data); // or $MySQL->query();
        return $something;
    } 
?>

Is this possible? Or has the second class being extending the first one?

Upvotes: 0

Views: 57

Answers (2)

Markus Kottl&#228;nder
Markus Kottl&#228;nder

Reputation: 8268

In the world of dependecy injection it woul look like this:

class MySQL {
    public function query($data){
        //do something
    }
}

class Users {
    private $mysql;

    public __construct($mysql){
        $this->mysql = $mysql
    }

    public function getUser($id){
        $this->mysql->query($data);
        return $something;
    } 
}

$mysql = new MySql();
$users = new Users($mysql);

Upvotes: 0

vaso123
vaso123

Reputation: 12391

If you want to access like this MySQL::query, then query method should be static.

Otherwise you need to instantiate a new object from MySQL class:

class Users {

    public function getUser($id) {
        //MySQL::query($data); //Static way
        $MySQL = new MySQL();
        $something = $MySQL->query($mydata);
        return $something;
    }
}

Upvotes: 2

Related Questions