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 $th开发者_C百科is->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
?>
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;
}
精彩评论