简体   繁体   中英

Can I make a function child of another Class without extends Class?

My Class is independant from another Class. Inside my Class, a function is doing the same but refined job as a function in another Class. Can I use parent:: function_in_another_class() and get my function join that parent funciton's job flow?

No.

In PHP you can only extend from none or one class. As you write both classes are independent to each other, there is no information where to find the one or the other class.

But what you're looking for is probably this:

class A
{
    function myFunction() {}
}

class B
{
    private $a;
    public function __construct(A $a)
    {
        $this->a = $a;
    }
    public function myFunction()
    {
        $this->a->myFunction();
    }
}

If any class method already doing the same thing why would you bother call join it?

You can not do it. If you want the same job flow best way to do is to instantiate the other class and invoke that very same method. Thats why we use OOP.

See the example,

interface Fable()
{
    public function f();
}

class OtherClass implements Fable
{
    public function f()
    {
      // job flow
    }
}

class MyClass
{
    private $fable;
    public function __construct(Fable $f)
    {
        $this->fable = $f;
    }

    public function method1($args){
        return $this->fable->f($args);
    }
}

If the current class is a child of another class, yes, you can. parent references to the parent class.

<?php
class A {
    function example() {
        echo "I am A::example() and provide basic functionality.<br />\n";
    }
}

class B extends A {
    function example() {
        echo "I am B::example() and provide additional functionality.<br />\n";
        parent::example();
    }
}

$b = new B;

// This will call B::example(), which will in turn call A::example().
$b->example();
?>

The best you can do here is to extend Class B from Class A

Class B extends Class A

But, you can also:

class ClassA {

  function do_something($args) {
    // Do something
    }

}

class ClassB {

  function do_something_inclassA($args) {
    classA::do_something($args);
    }

}

Important : calling classa::do_something(); is a static call, in other words with error reporting E_STRICT you will get a static notice warning because function do_something() is not static function do_something()

Also, calling this function statically (ie classa::do_something()) means that class a's function cannot refer to $this within it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM