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 make 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 cryptocurrency trader if you wonder what I am doing these days.
I found myself in need of doing overcharge of PHP constructor classes. If you are new to 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 overcharging by doing optional parameters. Other languages like C/C++ do 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 required 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 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!