【问题标题】:PHP static method call with namespace in member variable使用成员变量中的命名空间调用 PHP 静态方法
【发布时间】:2016-03-21 08:04:34
【问题描述】:

有可能在 php 中做这样的事情吗?我想在成员变量中有一个命名空间,并且总是能够像下面那样调用该类的每个静态方法。

当然我的代码不起作用,但我只是想知道这是否可能并且我已经接近解决方案,或者这完全不可能并且必须始终使用语法:

\Stripe\Stripe::setApiKey(..);

Similar question for clarifications

注意:我无法修改 Stripe 类,重要的是它在未来的开发者必须更新 Stripe API 时保持不变

简化代码:

class StripeLib
{
    var $stripe;

    public function __construct()
    {
        // Put the namespace in a member variable
        $this->stripe = '\\'.Stripe.'\\'.Stripe;
    }
}

$s = new StripeLib();

// Call the static setApiKey method of the Stripe class in the Stripe namespace
$s->stripe::setApiKey(STRIPE_PRIVATE_KEY);

【问题讨论】:

    标签: php namespaces


    【解决方案1】:

    是的,这样的事情是可能的。有一个静态的class方法可以调用,它返回类的命名空间路径。

    <?php
    namespace Stripe;
    
    Class Stripe {
    
        public static function setApiKey($key){
            return $key;    
        }
    
    }
    
    class StripeLib
    {
        public $stripe;
    
        public function __construct()
        {
            // Put the namespace in a member variable
            $this->stripe = '\\'.Stripe::class;
        }
    }
    
    $s = (new StripeLib())->stripe;
    
    // Call the static setApiKey method of the Stripe class in the Stripe namespace
    echo $s::setApiKey("testKey"); //Returns testkey
    

    【讨论】:

    • 感谢大安的及时答复。有没有办法让它工作而不必使用 $stripeLib,只使用 $s?我担心这会极大地混淆其他开发人员
    • @NaturalBornCamper 是的,当然,我已经编辑了我的答案。
    • 所以基本上这就像我链接的另一个问题一样,它绝对必须在一个常规变量中?不能是$this->member::setApiKey("testKey")的形式?
    • 不,很遗憾没有。
    • 好的,谢谢,我想这不是我真正希望的,因为您确实回答了我的问题,告诉我不可能按照我想要的方式去做,所以谢谢! :)
    【解决方案2】:

    我刚刚测试过,是的,你可以在 php 中做到这一点。

    但我认为你在这里违反了依赖注入原则。 正确的做法是:

    class StripeLib
    {
        var $stripe;
    
        // make sure Stripe implements SomeInterface
        public function __construct(SomeInterface $stripe)
        {
            // Stripe/Stripe instance
            $this->stripe = $stripe;
        }
    }
    

    【讨论】:

    • 有趣的回答 Keloo,谢谢。但是,我无法编辑 Stripe 类,它是一个官方 API,我希望在未来的开发人员在我离开后更新库时保持它的完整性,而不想知道它为什么会损坏;)应该提到这一点,我会现在就做
    猜你喜欢
    • 2014-01-31
    • 1970-01-01
    • 2017-05-20
    • 1970-01-01
    • 1970-01-01
    • 2012-07-22
    • 1970-01-01
    • 1970-01-01
    • 2011-09-28
    相关资源
    最近更新 更多