如何创建一个动态扩展类的工厂,使其类型发生变化但继承父方法?

发布于 2024-08-20 11:45:00 字数 832 浏览 4 评论 0原文

我想做的是有一个静态工厂函数,您可以提供一系列属性,并且它返回一个对象,该对象属于先前未声明的类,该类扩展了已知类。

基本上:

<?php
class foo {
  public $a;

  function increment($b = 1){
    $this->a += $b;
  }
}

function factory($name, $a){
  //returns an object of class $name that extends foo with $this->a set to $a
}

这样,如果我编写代码:

<?php
$bar = factory("bar",12);
$bar->increment(5);
print_r($bar);
if(is_a($bar, "foo")){
  echo "is a Foo";
}
$moo = factory("moo", 4);
$moo->increment();
print_r($moo);
if(is_a($moo, "foo")){
  echo "is a Foo";
}

我得到:[edit]

bar Object
(
    [a] => 17
)
is a Foo
moo Object
(
    [a] => 5
)
is a Foo

但我不知道从哪里开始寻找执行此操作所需的命令。我认为在我的工厂函数中,我需要以某种方式声明 $name 的值扩展父类,但不对其进行任何更改,然后构造一个新的 $name 。这样它就具有父类的所有功能,只是类型不同。

What I would like to do is have a static factory function that you can give a series of attributes and it returns an object that is of a previously undeclared class that extends a known class.

Basically:

<?php
class foo {
  public $a;

  function increment($b = 1){
    $this->a += $b;
  }
}

function factory($name, $a){
  //returns an object of class $name that extends foo with $this->a set to $a
}

so that if I write the code:

<?php
$bar = factory("bar",12);
$bar->increment(5);
print_r($bar);
if(is_a($bar, "foo")){
  echo "is a Foo";
}
$moo = factory("moo", 4);
$moo->increment();
print_r($moo);
if(is_a($moo, "foo")){
  echo "is a Foo";
}

I get: [edit]

bar Object
(
    [a] => 17
)
is a Foo
moo Object
(
    [a] => 5
)
is a Foo

But I don't know where to start looking for the commands necessary to do this. I think that in my factory function I need to somehow declare that the value of $name extends parent class but makes no changes to it, then constructs a new $name. That way it has all the functionality of the parent class, just a different type.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

春庭雪 2024-08-27 11:45:00

查看 PHP 反射 API 是否有您需要提取和构建新类的方法,但是,我不确定如何去做,然后创建它的实例。我确实知道这是可能的,因为我很确定这就是 PHPUnit 中 Mocking 的工作原理。您可能还想查看 PHPUnit 中与 Mock 对象相关的各种类以获得一些想法。

也就是说,除非您实际上要添加/重载方法,否则为什么要这样做呢?为什么不只使用对象中的属性或使用接口?这里的目标是什么?

Check out the PHP reflection API has the methods you need to extract and build the new class there but, how to go about doing it and then creating an instance of it im not sure of. I do know its possible though because im pretty sure this is how Mocking works in PHPUnit. You might also want to look at the various Mock object related classes in PHPUnit to get some ideas as well.

That said unless you are actually adding/overloading methods, why would you even want to do this? Why not just use a property in the object or use a an interface? Whats the goal here?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文