1

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();
    }
}    
2
  • Of course this is acceptable! Commented Feb 15, 2013 at 16:58
  • No, it is not acceptable. Commented Feb 17, 2013 at 10:48

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.