0

I'm not sure with my approach. A have two classes and call functions of first class in second class like this:

class A {

    public function aClassFunction() {...}

}


class B {

    private $aClass;

    public function __construct() {
        $this->aClass = new A();
    }

    public function bClassFunction() {
        $test = $this->aClass->aClassFunction();
    }
}

It just works, but looks "suspiciously".

3
  • As you said: it works. But if you want you can just use extends like: class B extends A and then you can use the function from the class A in class B Commented Feb 16, 2015 at 19:51
  • why not extend or better yet pass A as a dependency, through B's constructor? Theres even traits.. try abit more reasearch Commented Feb 16, 2015 at 19:52
  • I didn't know, how to explain it to google properly. Thanks Commented Feb 16, 2015 at 20:17

2 Answers 2

1

You can use dependency injection in B class. That approach helps you mocking classes in test.

class B {

    private $aClass;

    public function __construct(A $a) {
        $this->aClass = $a;
    }

    public function bClassFunction() {
        $test = $this->aClass->aClassFunction();
    }
}

$b = new B(new A());
Sign up to request clarification or add additional context in comments.

Comments

1

Looks "suspiciously" like a dependency. Why not Inject the Dependency?

class B {

    private $aClass;

    public function __construct($object) {
        $this->aClass = $object;
    }

    public function bClassFunction() {
        $test = $this->aClass->aClassFunction();
    }
}

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.