Ask the following class instantiation invocation problem.

below I give two classes a (assuming a contains a lot of functions) and b (just calling);

a code

namespace demo;

class a{
    public function index(){
        return "index";        
    }
    
    public function demo(){
        return "demo";        
    }
}

I often get called like this:

use demo\a;

class b{
    static function Amode (){
        return new a;
    }
    
    public Bindex(){
        echo self::Amode()->index();
    }
    
    public Bdata(){
        echo self::Amode()->demo();
    }
    
}

does the above method work better than the bottom?

use demo\a;

class b{
    
    public Bindex(){
        $mode=new a();
        echo $mode->index();
    }
    
    public Bdata(){
         $mode=new a();
        echo $mode->demo();
    }
    
}

Php
Jun.16,2022

I think there is little difference between the two methods. If there is a better solution, you can learn about control inversion


.

the difference is whether the data of an is shared:

self::Amode()->index() //a
$mode=new a(); //a
echo $mode->index();
What

insists on is to ensure, to some extent, the singleton operation of a in class b .

Menu