我尝试在没有 MVC 模块的情况下使用来自 zf2 的 ServiceManager。我有两个文件:classServiceManager.php 和 sm.php。
1)类ServiceManager.php:
namespace ZF2;
use Zend\ServiceManager\ServiceManager;
use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use \InvalidArgumentException;
class classServiceManager implements ServiceLocatorAwareInterface{
protected $serviceLocator;
function __construct(){
//echo "SM: ". $this->getServiceLocator()->get('sm');
echo "SM: ".$this->serviceLocator->get('sm');
}
function setServiceLocator(ServiceLocatorInterface $serviceLocator) {
$this->serviceLocator = $serviceLocator;
}
function getServiceLocator() {
return $this->serviceLocator;
}
}
2) sm.php
$config = array(...);
require_once 'Zend/Loader/AutoloaderFactory.php';
Zend\Loader\AutoloaderFactory::factory($config);
......
use ZF2\classServiceManager;
$serviceManager = new ServiceManager();
$serviceManager->setService('sm', 'aaa');
$a = new classServiceManager();
但是当我运行时sm.php
,我得到一个错误:
Fatal error: Call to a member function get() on a non-object....