fork download
  1. <?php
  2.  
  3. ini_set('display_errors', 1);
  4.  
  5. class ParentClass
  6. {
  7. public function __construct()
  8. {
  9.  
  10. }
  11.  
  12. public static function create()
  13. {
  14. $class = get_called_class();
  15. return new $class;
  16. }
  17.  
  18. public static function testMethod()
  19. {
  20. echo 'this should work in both classes'.PHP_EOL;
  21. }
  22.  
  23. }
  24.  
  25. class ChildClass extends ParentClass
  26. {
  27.  
  28. public function __construct(string $param1 = 'test', string $param2)
  29. {
  30.  
  31. }
  32.  
  33. }
  34.  
  35. function testClass(ParentClass $class)
  36. {
  37. $object = $class::create();
  38. $object::testMethod();
  39. }
  40.  
  41. testClass(new ParentClass());
  42. testClass(new ChildClass('1', '2'));
  43.  
  44.  
  45.  
Runtime error #stdin #stdout #stderr 0.01s 82880KB
stdin
Standard input is empty
stdout
this should work in both classes

Fatal error: Uncaught ArgumentCountError: Too few arguments to function ChildClass::__construct(), 0 passed in /home/ro35GN/prog.php on line 16 and exactly 2 expected in /home/ro35GN/prog.php:29
Stack trace:
#0 /home/ro35GN/prog.php(16): ChildClass->__construct()
#1 /home/ro35GN/prog.php(38): ParentClass::create()
#2 /home/ro35GN/prog.php(43): testClass(Object(ChildClass))
#3 {main}
  thrown in /home/ro35GN/prog.php on line 29
stderr
PHP Fatal error:  Uncaught ArgumentCountError: Too few arguments to function ChildClass::__construct(), 0 passed in /home/ro35GN/prog.php on line 16 and exactly 2 expected in /home/ro35GN/prog.php:29
Stack trace:
#0 /home/ro35GN/prog.php(16): ChildClass->__construct()
#1 /home/ro35GN/prog.php(38): ParentClass::create()
#2 /home/ro35GN/prog.php(43): testClass(Object(ChildClass))
#3 {main}
  thrown in /home/ro35GN/prog.php on line 29