PHP从子类工厂方法调用超类工厂方法 [英] PHP Call Superclass Factory Method from Subclass Factory Method

查看:65
本文介绍了PHP从子类工厂方法调用超类工厂方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写带有子类的php应用程序,并且由于我想拥有多种创建对象的方法,因此我在使用不同的工厂方法而不是多个构造函数.

I am writing a php app with subclasses and since I want to have multiple ways to create an object I am doing different factory methods instead of multiple constructors.

我有一个具有工厂方法的 User

I have a User with factory methods

User::from_id
User::from_netid

我有几个 User 的子类.我以前曾调用父超构造函数,但是当我切换到工厂方法时,该构造函数不存在.

I have several subclasses of User. I was previously calling the parent superconstructor, but when I switched to the factory method that constructor didn't exist.

我有 Student ,这是 User 的子类.为了使其正常工作,我不得不将 User :: from_id 中的几乎所有超类工厂代码复制到 load_by_id ,因为在这种情况下实例已经存在:

I have Student, a subclass of User. To get it to work, I had to duplicate almost all of my superclass factory code in User::from_id to load_by_id, since in this situation the instance already existed:

// In Student.php - Student extends User
public static function from_id_and_course($id, $course){
    $instance = new self();
    $instance->load_by_id($id);
    $instance->course = $course;
    ...
}

我想从子类中调用超类工厂方法作为起点,然后继续添加其他字段.像这样...

I want to call the superclass factory method from the subclass as a starting point, and then continue to add the other fields. Something like this...

$instance = User::from_id($id);

$instance = Student::from_id($id);

,但是在这些情况下,它给了我一个 User 对象,并且我需要一个 Student 对象.我能做到这一点的唯一方法是执行 $ instance = new self().

but in these cases it gives me a User object, and I need a Student object. The only way I could accomplish this is by doing $instance = new self().

如何从子类调用超类工厂方法作为创建新子类工厂方法的起点?

How can I call the superclass factory method from the subclass as a starting point to create a new subclass factory method?

推荐答案

您的问题是这个

$instance = new self();

self 是指定义方法的类,而不是调用方:

self refers to the class where the method is defined, not the caller:

  • 调用 Student :: from_id()时,如果它不存在,则会退回到 User :: from_id().
  • User :: from_id()中, self 是指 User ,而不是 Student .
  • When Student::from_id() is called, if it doesn't exist, it falls back to User::from_id().
  • In User::from_id(), self refers to User, not Student.

您必须使用后期静态绑定:

$instance = new static();

但是,像往常一样,我强烈建议您反对它.与对象范围相比,使用对象范围更好.扩展,伪造或模拟以及偶然进行测试更容易.

However, like I always do, I'd highly recommend against it. You're better off using the object scope than the static scope. It's easier to extend, to fake or mock and incidentally, to test.

没有问题:

$user = new User;
$user->from_id($id);

$student = new Student;
$student->from_id($id);

...实际上更好.

这篇关于PHP从子类工厂方法调用超类工厂方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆