我想在某些对象中存储一些配置数据,但我有一个问题...
class B {
const attr1 = 'something1';
const attr2 = 'something2';
const attr3 = 'something3';
}
class A {
const attr1 = 'somethingA1';
const attr2 = 'somethingA2';
const attr3 = 'somethingA3';
const b = <---- i wanna put here a reference of B, but B as a class (not an object...), i'm crazy?
}
我不确定我的例子是否清楚...从 A 开始,我想访问 B 的 attr1,例如 A::B::attr1,或者类似的东西,还有另一种方法可以做到这一点吗?还是我错了?
没有办法分配对类的引用,也没有办法在运行时分配类常量。所以你的整个方法几乎是不可能的。你能做的是
const b = 'B'
从 PHP 5.3.0 开始,您可以这样做
$b = A::b;
echo $b::attr1;
但你不能做A::b::attr1
.这将引发T_PAAMAYIM_NEKUDOTAYIM
错误。这是一个解析器限制。在撰写本文时,PHP 无法执行此操作。
因为类 B 包含 A 的一组数据,我想在 b(的 A(中存储一个复杂的数据,我想这样做是因为我想保持代码干净
您可以通过使B
成为A
的复合物来轻松解决此问题,例如,在创建A
时,您可以将B
注入A
class A
{
private $b;
public function __construct(B $b)
{
$this->b = $b;
}
}
$a = new A(new B);
或在A
内部创建B
,例如
class A
{
private $b;
public function __construct()
{
$this->b = new B;
}
}
因为B
只是A
的数据部分,所以你通过隧道通过A
而不是掌握B
然后使用B的方法。因此,任何使用 A
的代码都不需要知道 A
内部有一些B
。这将允许您轻松更改B
,而无需担心消耗A
的代码,例如,为了获得attr1
,您将 getter 添加到 A
:
public function getAttr1()
{
$b = $this->b;
return $b::attr1;
}
在B
中使用属性而不是常量时,您可以减轻笨拙的赋值需求(无论如何,常量在 PHP 中是愚蠢的,因为您必须将它们视为公共 API(,例如
class B
{
private $attr1;
public function getAttr1()
{
return $this->attr1;
}
}
然后你可以做A
:
public function getAttr1()
{
return $this->b->getAttr1();
}
更好的做法是不要完全通过A
公开B
的内部结构,而只添加对 A 执行某些操作的公共方法。这将使您的 API 更小,您的代码更具 OO。
你不能引用这样的类,因为你使用该类的唯一方法是通过一个对象,所以尝试这样做也没有意义。
用户此:
class A {
const attr1 = 'somethingA1';
const attr2 = 'somethingA2';
const attr3 = 'somethingA3';
public $b;
function __construct() {
$this -> b = new b();
}
你可以简单地说b = "B"
..
而如果要创建B的对象,可以做new b
或者访问属性