【问题标题】:php: Confused about the way the "use" keyword is used in this code snippetphp:对这段代码片段中使用“use”关键字的方式感到困惑
【发布时间】:2014-04-10 13:17:41
【问题描述】:

found a question on SO 以我不理解的方式使用了 php“use”关键字。这是代码sn-p:

<?php
namespace My;

use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorAwareTrait;

class MyClass implements ServiceLocatorAwareInterface{
    use ServiceLocatorAwareTrait;


    public function doSomething(){
        $sl = $this->getServiceLocator();
        $logger = $sl->get( 'My\CusomLogger')
    }
}

// later somewhere else
$mine = $serviceManager->get( 'My\MyClass' );

//$mine now has the serviceManager with in.

现在我在没有use ServiceLocatorAwareTrait; 行的情况下尝试了这段代码,但它不起作用。当页面顶部已经有use Zend\ServiceManager\ServiceLocatorAwareTrait; 时,为什么还要使用use ServiceLocatorAwareTrait;。这像是用默认值初始化接口所需的方法的特殊方法吗?

【问题讨论】:

  • 一个是命名空间。一个包括一个特征。
  • 哇,甚至不知道什么是“特征”。我有一些阅读要做谢谢。
  • 然后给你:php.net/manual/en/language.oop5.traits.php(特征是 PHP 5.4+)

标签: php oop interface


【解决方案1】:

类声明之外的“使用”是导入其他命名空间 - 类/接口。

Class 声明中的一个是将 Trait 导入到 Class 中,因此该类可以访问 trait 的行为。

命名空间 - http://php.net/manual/en/language.namespaces.php 特征 - http://php.net/manual/en/language.oop5.traits.php

【讨论】:

    猜你喜欢
    • 2012-10-05
    • 1970-01-01
    • 2017-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多