osoclever
osoclever

Reputation: 373

accessing a class from another class

I have an idea which requires loading in another class. Let's say I have index.php that includes once (database.php). In a class, is it acceptable to create a new object that is not extended by the class? In otherwords, brining in the content globally instead? Here's what I mean...

index.php:
----------------------
include_once ('./core/dataAccess.php');

....

class home {
    private function getUsers() {
        $dataAccess = new DataAccess();
    }
}    

Upvotes: 1

Views: 68

Answers (1)

Fabian Schmengler
Fabian Schmengler

Reputation: 24576

It's acceptable and widely used practice, however it is in most cases not the best solution. The advanced way is using dependency injection, which means that any other objects needed by your class will be " injected" from the outside, making them interchangeable. This could happen in the constructor, in a setter method or directly as parameter where they are needed.

The only methods that use the new keyword are then factory methods that do nothing else than creating objects.

Upvotes: 2

Related Questions