User Rating: 5 / 5

Star Active Star Active Star Active Star Active Star Active

This weekend I learned something new while coding in PHP. Not really a fan of PHP, but it has a lot of libraries I need that makes coding faster. Later when this project is finished, I might recode it in C/C++ without a rush. By the way, I am coding a crypto currency trader if you wonder what I am doing these days.

I found myself in the need of doing overcharge of PHP constructor classes. If you are new on PHP coding, overcharge is the capability that some languages have to define the same function with different parameters.

For example, you could call a function like this:

my_function(param1, param2, param3);



PHP allows overcharge by doing optional parameters. Other languages like C/C++ does it in a very different way, in my opinion, more classy than PHP.

PHP has a little restriction, you can not overcharge class constructors. If you try it, you will get some errors. My issue was that was in need of setting up something that allows two or four parameters, not three, not five, not zero. I must say this technique is not mine, I found it on the net, but it is quite interesting and I am documenting it. Here it is the code sample I used:

class poloniex {
  protected $api_key;
  protected $api_secret;
  protected $trading_api_key;
  protected $trading_api_secret;
  protected $trading_url = "";
  protected $public_url = "";

  public function __construct(){
    $a = func_get_args();
    $i = func_num_args();
    if (method_exists($this,$f='__construct'.$i)){
      throw new Exception('Incorrect number of parameters, 2 or 4 only.');

  public function __construct2($api_key, $api_secret){
    $this->api_key = $api_key;
    $this->api_secret = $api_secret;
    $this->trading_api_key = $api_key;
    $this->trading_api_secret = $api_secret;

  public function __construct4($api_key, $api_secret, $trading_api_key, $trading_api_secret){
    $this->api_key = $api_key;
    $this->api_secret = $api_secret;
    $this->trading_api_key = $trading_api_key;
    $this->trading_api_secret = $trading_api_secret;

This code is taking advantage of func_get_args(), func_num_args() and call_user_funct_array(). Note how I had to define functions __construct2() and __construct4(). I bet there are more elegant and much more complex ways to do this, but this is enough for what I need.

Good luck!

blog comments powered by Disqus