Home  >  Q&A  >  body text

About chain calls in PHP

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!

天蓬老师天蓬老师2701 days ago805

reply all(2)I'll reply

  • 为情所困

    为情所困2017-06-19 09:09:08

    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.

    reply
    0
  • typecho

    typecho2017-06-19 09:09:08

    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();

    reply
    0
  • Cancelreply