0

I'm new to PHP. I have three classes, say A, B, and C, where B and C inherit directly from A. My problem is, I need a static factory, say createInstance() that is defined once for class A, and is applicable throughout its descendants. So when someone calls A::createInstance(), it returns an object of type A, while calling B::createInstance() returns an instance of B, and C::createInstance() returns an instance of C. I put the following code inside createInstance() definition in class A:

public static function createInstance() {
    return new self();
}

but that wouldn't be the solution to my needs, since self always refers to class A regardless of what class it's called on. In other words, calling B::createInstance() and C::createInstance always return an object of type A. How can I create such a factory method that returns an object of the appropriate class?

1 Answers1

2

PHP has a static keyword you can use:

public static function createInstance() {
    return new static();
}
Anonymous
  • 11,748
  • 6
  • 35
  • 57
  • Dear Anonymous, I learned Java with Deitel's 'Java How to Program' book. It was so useful, since it taught pretty much every and each of details of Java. It scrutinizes everything (perhaps too much). Unfortunately Deitel hasn't written such a book about PHP. I really need one such book, but haven't found any. Do you know such a book that explains details of how the language works? – Hedayat Mahdipour Dec 25 '19 at 21:23
  • 1
    @HedayatMahdipour I don't anything will be better than reading [the PHP documentation](https://www.php.net/manual/en/). You don't have to read all of it but it has the most updated information and lots of examples. – Anonymous Dec 25 '19 at 21:29
  • On a very similar thread the top rated answer says that this pattern should be avoided. I don't want to overindex on that user's opinion, so I'd be curious @Anonymous if you think this is a fine pattern to use... Here's the other question: https://stackoverflow.com/questions/8583989/php-call-superclass-factory-method-from-subclass-factory-method – gen May 29 '20 at 13:41
  • @gen I’ve never needed this pattern, but it might be ok when all subclasses are known. There’s usually a better way. For example, in the linked question, I don’t see why `User` needs that method too. I would use a trait instead – Anonymous Aug 11 '20 at 20:27