亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

About chain calls in PHP
天蓬老師
天蓬老師 2017-06-19 09:07:08
0
2
990

I encountered a problem when using PHP chain calls:
There is a class "Site" below:

<?php
class Site{
public function api(){
require('class.Api.php');
$this->api = new Api();
return $this->api;
}
}
?>

There is also a class "Api" located in "class.Api.php":

<?php
class Api{
public function auth(){
//quiet a few
}
public function render(){
//quiet a few
}
}
?>

Use the following code to instantiate:

$site = new Site();

Call the following code again:

$site->api()->auth();
$site->api()->render();

Will PHP repeat require() and create new object API? If so, require() can be replaced by require_once(), but how to make "$site->api()" return the same object? Thanks!

天蓬老師
天蓬老師

歡迎選擇我的課程,讓我們一起見證您的進(jìn)步~~

reply all(2)
為情所困

Single case mode.

<?php
class Site{
    
    public function api(){
        if (!isset($this->api)) {
            $this->api = new Api();
        }
        return $this->api;
    }
}
?>

It’s just a simple writing, but it still needs a lot of optimization.

typecho
require('class.Api.php');
class Site{
    protected $api;
    
    public function getApi()
    {
        return $this->api;
    }
    
    public function api(){
        $this->api = new Api();
    }
}
?>
$site = new Site();
$site->api();
$site->getApi()->auth();
$site->getApi()->render();
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template