user479947
user479947

Reputation:

Passing a reference to a class

I have a $database object that I need to reference inside another class.
Would this be the right way to do that?

<?php
class User {
  private $database;

  function getPosts($limit = 1) {
    return $this->database->query("select...");
  }

  function __construct(&$database) {
    $this->database = $database; // Do I need an another ampersand here?
  }
}

$user = new User($database); // $database is defined in an earlier include
?>

Upvotes: 1

Views: 84

Answers (1)

BoltClock
BoltClock

Reputation: 723729

From the looks of it, you don't need any ampersands. No matter how many references you have they should all refer to the same $database object.

  function __construct($database) {
    $this->database = $database;
  }

Upvotes: 2

Related Questions