简体   繁体   English

PHP:从父方法中的静态方法调用子构造函数

[英]PHP: call child constructor from static method in parent

I want to have a static method in a parent class that creates instances of whatever subclass i call this method on. 我希望在父类中有一个静态方法,它创建我调用此方法的子类的实例。

An example to make this more clear: 举个例子来说明这一点:

class parent {
    public static method make_objects($conditions){
        for (...){
            // here i want to create an instance
            // of whatever subclass i am calling make_objects on
            // based on certain $conditions
        }
    }
}

class sub extends parent{
    ...
}

$objects = sub::make_objects($some_conditions);

As of php 5.3 you can use the static keyword for this 从php 5.3开始,您可以使用static关键字

<?php
class A {
  public static function newInstance() {
    $rv = new static();  
    return $rv;
  }
}
class B extends A { }
class C extends B { }

$o = A::newInstance(); var_dump($o);
$o = B::newInstance(); var_dump($o);
$o = C::newInstance(); var_dump($o);

prints 版画

object(A)#1 (0) {
}
object(B)#2 (0) {
}
object(C)#1 (0) {
}

edit: another (similar) example 编辑:另一个(类似的)例子

<?php
class A {
  public static function newInstance() {
    $rv = new static();  
    return $rv;
  }

  public function __construct() { echo " A::__construct\n"; }
}
class B extends A {
  public function __construct() { echo " B::__construct\n"; }
}
class C extends B {
  public function __construct() { echo " C::__construct\n"; }   
}

$types = array('A', 'B', 'C');
foreach( $types as $t ) {
  echo 't=', $t, "\n";
  $o = $t::newInstance();
  echo '  type of o=', get_class($o), "\n";
}

prints 版画

t=A
 A::__construct
  type of o=A
t=B
 B::__construct
  type of o=B
t=C
 C::__construct
  type of o=C

I think you want something like this: 我想你想要这样的东西:

class parent {
  public static function make_object($conditionns) {
    if($conditions == "case1") {
      return new sub();
    }
  }
}

class sub extends parent {

}

Now you can create an instance like this: 现在您可以创建一个这样的实例:

$instance = parent::make_object("case1");

or 要么

$instance = sub::make_object("case1");

But why would you want all the sub classes to extend the parent? 但是为什么你想要所有子类扩展父类? Shouldn't you much rather have a parent for your models (sub classes) and then a factory class, that creates the instances for this models depending on the conditions given? 你不应该更喜欢你的模型(子类)和工厂类的父级,它根据给定的条件为这个模型创建实例吗?

Umm, wouldn't that be: 嗯,不会那样:

class sub extends parent {
  public static function make_objects($conditions) {
    //sub specific stuff here
    //....
  }
}

make the parent class an abstract class and make the parent method also an abstract 使父类成为一个抽象类,并使父方法也成为一个抽象类

abstract static class parent {
     abstract function make_method() {
         // your process
     }
}

class child extends parent {
     public function __construct() {
          parent::make_method();
     }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM