0

Im new to classes and I dont really know how to do this. Since Im new to using classes and very bad at searching I decided to ask here. What I want is a function from a class passed to another function in a class.

I tried to call it as below but it couldnt find the variable $b

For example:

class a {

function one() {

$b->two();

}

}

class b {

function two() {

echo "two";

}

}

$a = new a();
$b = new b();

How do i achieve this?

Thanks in advance!

4 Answers 4

3

You need to learn about Dependency Injection. In this case, A depends on B, so you need to pass it into A when instantiating A. Also, it's the standard naming convention to capitalize class names. It helps readability.

class A {
  public function __construct(B $B) {
    $this->B = $B;
  }
  public function one() {
    $this->B->two();
  }
}

class B {
  public function two() {
    echo "two";
  }
}

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

2 Comments

Problem is, I've already decleared __construct for passing the database to the class.
That isn't any problem..just do the same thing in the constructor you already have. Pass it $Database and $B and set them both to $this. @ilpaijin's answer is another way you can do this using a mutator aka setter.
2

There are many ways to achieve it and a lot of things to say before this example, just by learning more u'll discover all by yourself. By the way one of them:

class A {

    public $b;

    public function __construct(B $b)
    {
        $this->b = $b;
    }

    function one() 
    {

        $this->b->two();
    }
}

class B 
{

    function two() 
    {

        echo "two";
    }
}

$b = new B();
$a = new A($b);

$a->one();

-------EDIT-------

After knowing that still use a constructor and in case you can't modify it, u need to use what is called an setter or mutator method.

class A {

    public $b;

    public function setB(B $b)
    {
        $this->b = $b;
    }
    ...
}

class B {

    ...
}

$b = new B();
$a = new A();

$a->setB($b);
$a->one();

Comments

0

You can't do it like that..

What you should read about is: "inheritance" in PHP.

basically doing this will allow you to achieve somewhat understanding of it:

class A extends B {
    function one() {
        $this->two();
    }
}

class B {
    function two() {
        echo "two";
    }
}

Comments

0
class a {
    function one() {
        $b = new b();
        $b->two();
    }
}

class b {
    function two() {
        echo "two";
    }
}

$a = new a();
$a->one();

Output:

two

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.