VoIP, Linux, Security & much more fun
If you need any help regarding these subjects do not hesitate about sending me a text

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);

and

my_function();

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 = "https://poloniex.com/tradingApi";
  protected $public_url = "https://poloniex.com/public";

  public function __construct(){
    $a = func_get_args();
    $i = func_num_args();
    if (method_exists($this,$f='__construct'.$i)){
      call_user_func_array(array($this,$f),$a);
    }
    else{
      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
If you need more help than the free one provided here...