开发者

Call function from class B in class A

I'm using PHP here, and I have two classes. Can I call a function from one class in the other one. For example:

class A
{
    function a_fu开发者_Python百科nc()
    {
        echo "A function";
    }
}

$a = new A();

class B
{
    function b_func()
    {
        $a->a_func();    // This is the thing I'm stuck with.
    }
}

I hope I've made myself clear here. I had a look on Google, but I don't know what this is called so I came up with nothing. Thanks for any help.


Pretty good answers so far. One thing that others have not mentioned yet...

If B requires an object A to work properly, you should pass one into the constructor and use object composition:

class B {

    protected $a;

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

    public function b_func() {
        $this->a->a_func();
    }

}

$a = new A;
$b = new B($a);
$b->b_func();

You'll see that I've made the $a property in class B protected. This is for encapsulation, definitely something you should read on.

Another important topic you should read on is dependency injection.


You have 2 workarounds: 1) If your a_func doesn't need an instance (seems it's the case), you can make the function static and call it from the second class

class A
{
    public static function a_func()
    {
        echo "A function";
    }
}

class B
{
    function b_func()
    {
        A::a_func(); 
    }
}

2) 1) If your a_func needs an instance, you're forced to create one:

class A
{
    public function a_func()
    {
        echo "A function";
    }
}

class B
{
    function b_func()
    {
        $a = new A;
        $a->a_func();
    }
}


You can, if you make $a local to b_func().

Either by

  • Declaring it global $a; inside b_func() (probably not a good idea, depends on your use case)

  • passing $a as a parameter to b_func():

    function b_func($a)
    ....
    
  • making $a a member of B:

    $b = new B();
    $b->a = new a();  // Can be accessed by  `b_func()` as `$this->a`#
    
  • or initializing $a inside b_func():

    function b_func()
    {
      $a = new A();
    

which is the best in your scenario will depen on what A and B do, and what relation they have.


You can call a_func() if you instantiate class A first:

class B
{
  function b_funct()
  {
    $a = new A(); //create instance of A
    $a->a_func(); //run function
  }
}

An alternative is make a_func static:

static function a_funct()

and call it as:

A::a_function();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜