Php在另一个类的构造函数中使用一个类,并在命名空间

时间:2015-06-02 07:43:05

标签: php oop composer-php

我使用作曲家更新了我前同事的Handler类Cosenary Instagram Class后的som遗留代码。

以前在处理程序类中包含类的引用是:

namespace Acme\Instagram;
class Handler
{ 

/* GOT SOME USEFUL VARS HERE */

const API_URL = 'https://api.instagram.com/v1';

/**
 * Initialize the library
 *
 * @param array  $settings Contains our ClientId and upload dir
 * @param string $root_dir The root of our application
 */
public function __construct( $settings, $root_dir = __DIR__ )
{
    include_once  $root_dir . '/vendor/cosenary/instagram/instagram.class.php'; //HERE WAS THE INCLUDE BEFORE


    // THROW SOME EXCEPTIONS HERE IF SETTINGS MISSING ETC...

    // New instance of the instagram class
    $this->_instagram = new \Instagram($this->_clientId);
}

/* HANDLE SOM FUNCTIONS HERE */

}

如果我将include_once更改为:

    require_once $root_dir . '/vendor/cosenary/instagram/src/Instagram.php';

然后我得到:

Fatal error: Class 'Acme\Instagram\Instagram' not found in

我想我需要将它作为构造函数中的引用传递,但这意味着我需要重写大量代码,并且可能有5-10个其他项目依赖于这个Hanlder类。有没有办法在另一个类中使用instagram类?

尝试移出include_once并:

use MetzWeb\Instagram\Instagram;

但没有运气,任何帮助或指示我非常感激。

1 个答案:

答案 0 :(得分:1)

我不确定你的应用程序的结构如何。 但试试这个:

namespace Acme\Instagram;

require_once $root_dir.'/vendor/autoload.php';

use MetzWeb\Instagram\Instagram AS InstagramClient;

class Handler
{ 

/* GOT SOME USEFUL VARS HERE */

const API_URL = 'https://api.instagram.com/v1';

/**
 * Initialize the library
 *
 * @param array  $settings Contains our ClientId and upload dir
 * @param string $root_dir The root of our application
 */
public function __construct( $settings, $root_dir = __DIR__ )
{
    // New instance of the instagram class
    $this->_instagram = new InstagramClient($this->_clientId);
}

/* HANDLE SOM FUNCTIONS HERE */