可以在php中做这样的事情吗?我想在成员变量中有一个命名空间,并且总是能够调用该类的每个静态方法,就像我在下面所做的那样。
当然,我的代码不起作用,但我只是想知道这是否可能,并且我接近解决方案,或者这是否完全不可能并且必须始终使用语法:
'Stripe'Stripe::setApiKey(..);
需要澄清的类似问题
注意:我无法修改 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);
是的,这样的事情是可能的。有一个可以调用的静态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
我刚刚测试了它,是的,你可以在 php 中做到这一点。
但我认为你在这里违反了依赖注入原则。正确的方法是:
class StripeLib
{
var $stripe;
// make sure Stripe implements SomeInterface
public function __construct(SomeInterface $stripe)
{
// Stripe/Stripe instance
$this->stripe = $stripe;
}
}