Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.8k views
in Technique[技术] by (71.8m points)

oop - Sharing objects between PHP classes

What is the best way to share objects between other classes?

For example; a "database" object with functions that are required by the "article" and "user" objects.

I don't want to use globals (that includes singletons) or create a new instance of the object in each class, such as

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

Would passing the objects in, eg.

class test{
    function __construct( $obj ) {
        $this->obj = $obj;
    }
}
$database = new database;
$test = new test( $database );

Be the way to go?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Yes. Passing the objects to the constructor - or to a setter - is the best way to go. This pattern is known as dependency injection. It has the added benefit that it makes your code easier to test (using stubs or mocks).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...