php 如果使用App::init(),则返回NULL;

lsmd5eda  于 2023-03-16  发布在  PHP
关注(0)|答案(1)|浏览(63)

我在php中练习设计模式(单例和依赖注入),问题是当我在run(){}中设置另一个索引文件来设置和测试路由时,如果在新的索引文件中从Applaction类创建另一个示例:

  • 如果我使用Applaction::init()作为函数将返回NULL ;
  • 但是如果我使用Applaction::$init;..威尔工作得很好!!!
<?php 
namespace System;
class Applaction{

 public static $init = null; //instance    
 
 public Array $container = [];

 private function __construct(File $file)
{
        static::$init = $this;

        $this->share('files', $file); 

        $this->setClasses();

        $this->loadFunctions();
}

//create class instance    
public static function init($file = null){
    if(is_null(static::$init)){
        static::$init = new static($file);
        return static::$init;
    }
}

public function run(){
    $this->session->start();

    //use App/index.php File for test 
    $this->files->getFiles('App/index.php');

    $this->request->setUrl();

    list($controller, $method, $args) = $this->route->getProperRoute(); 

    $this->load->controller($controller);
}

//可以正常工作

<?php 
 //App\index.php

 use System\Applaction;

 $app =  Applaction::$init; // $init ?!

$app->route->add('/', 'Home');

此处返回NULL

<?php 

 //App\index.php

 use System\Applaction;

 $app =  Applaction::init(); // method init()

$app->route->add('/', 'Home');
pjngdqdw

pjngdqdw1#

谢谢大家...
更新:

class Application{

 public static $instance = null;   
 
 private Array $container = [];

 private function __construct($file = null)
{
        //self::$instance = $this;

        $this->share('files', $file); 

        $this->setClasses();

        $this->loadFunctions();
}

public static function getInstance($file = null){
    if(is_null(self::$instance)){
        self::$instance = new static($file);
    }

    return self::$instance;
}

public function run(){
    $this->session->start();

    $this->files->getFiles('App/index.php');

    $this->request->setUrl();

    list($controller, $method, $args) = $this->route->getProperRoute(); 

    $this->load->action($controller, $method, $args);
}

相关问题