开发者

Why some variables are parameters and others aren't?

What could be the reason for having this:

public function __construct($host, $port, $timeout = 5){
    $errnum = 0;
    $errstr = ''; 

Instead of this:

public function __construct($host,开发者_Python百科 $port, $errnum = 0, $errstr = '', $timeout = 5){

?

Why some are params and others aren't ?

Thanks a lot, MEM


A function definition defines a contract between the function itself and the code that calls it.

A variable should only be a parameter if the caller should specify it's value. Otherwise if a variable is only used internally by the function, there is no need to specify it as a parameter.


the errors are set by the function, and there is no point passing those in


If they would be params, the user could pass them in during the creation of the object. A call like

$a = new MyObject($myhost, $myport, 40000, 'Failed.', $mytimeout);

would initialize your object with an error already in its memory... In the case of an error number or string, that is rather unwanted. The user shouldn't be able to poke a random error into your object.


Normally you define a function in a way that it only accepts parameters/data that it definitely needs in order to run.

In you example, $errnum and $errstr seem to be variables that the function uses internally. If you design that function you have to decide whether you want to give the user the possibility to override those or not.


Maybe you want to call the constructor with more than 3 parameters, depending on what the constructor/class do. The parameter list is not the place to initialize local variables. Check the API of the class you are reading what the parameters are for (looks like they are for the fsockopen function, so read this documentation first).


$timeout is a default parameter that can be overwritten when calling the function.

$errnum and $errstr cannot be overwritten when calling the function.

Observe:

public function goodConstruct($host, $port, $timeout = 5){
    $errnum = 0;
    $errstr = ''; 
}

goodConstruct('hostname',8443,60);

By doing this, I can overwrite the default timeout.

public function badConstruct($host, $port, $errnum = 0, $errstr = '', $timeout = 5)
{

//code
}

badConstruct('hostname',8443,99,'hey look at this silly error!!!!',900);

Now I can also overwrite the error code (assuming that's the purpose of errnum, it's even worse if that's some sort of a counter) and the error string. Do you really want to be able to control this from your function call? Probably not... I assume that you'd want that to be fixed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜