Jacob
Jacob

Reputation: 2071

Class function in another class function

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!

Upvotes: 0

Views: 60

Answers (4)

ilpaijin
ilpaijin

Reputation: 3695

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();

Upvotes: 2

m59
m59

Reputation: 43755

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();

Upvotes: 3

Amal Murali
Amal Murali

Reputation: 76656

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

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

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

Output:

two

Upvotes: 0

deb0rian
deb0rian

Reputation: 976

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";
    }
}

Upvotes: 0

Related Questions