agorlov/php-constructor-overloading

PHP中的多重构造函数

1.0.1 2018-09-16 19:24 UTC

This package is not auto-updated.

Last update: 2024-09-24 23:50:23 UTC


README

类似于Java或C++中的构造函数重载PHP方法

基于文章(如何将此技术从Java迁移到PHP)

https://www.yegor256.com/2015/05/28/one-primary-constructor.html

适用于PHP > 7

如何安装

$ composer require agorlov/php-constructor-overloading

使用示例

use AG\OverloadedConstructor;


final class Cash {
  /** @var int */
  private $cents; 
  /** @var string */
  private $currency;
  
  private function constrEmpty() { // secondary
    $this->__construct(0);
  }
  
  private function constrCnts(int $cts) { // secondary
    $this->__construct($cts, "USD");
  }
  
  private function constrPrimary(int $cts, string $crn) { // primary
    $this->cents = $cts;
    $this->currency = $crn;
  }
  
  public function __construct() {
    // overloaded constructors invocation
    $method = (new OverloadedConstructor($this, func_get_args()))->constructor();
    $this->$method(...func_get_args());  
  }
  
  // methods here
}

var_dump(new Cash());

更多示例:在 example.phpexample2.php

有效的标量提示

  • array
  • callable
  • bool 不是 boolean!
  • float 不是 double!
  • int 不是 integer!
  • string
  • iterable
  • object

测试

$ composer install
$ vendor/bin/phpunit OverloadedConstructorTest.php