为什么/如何在函数中使用传递的常量? [英] Why/How to use passed constants in function?
问题描述
我已经看过常量传递给方法的类,我想它在该函数中定义了一些设置。我不能找到它在任何地方,试图找出逻辑,所以我虽然我可以问这里。如何和为什么使用这个概念,我在哪里可以找到更多的信息?
I've seen classes where constants are passed to methods, I guess its done to define some kind of setting in that function. I cant find it anywhere now to try to find out the logic, so I though I could ask here. How and why do you use this concept and where can I find more information about it?
下面的例子是用PHP编写的,但任何处理常量的语言都可以。
The example below is written in PHP, but any language that handles constants would do I guess..
// Declaring class
class ExampleClass{
const EXAMPLE_CONST_1 = 0;
const EXAMPLE_CONST_2 = 1;
function example_method($constant(?)){
if($constant == ExampleClass::EXAMPLE_CONST_1)
// do this
else if($constant == ExampleClass::EXAMPLE_CONST_2)
// do that
}
}
// Using class
$inst = new ExampleClass();
$inst->example_method(ExampleClass::EXAMPLE_CONST_1);
对我来说,比传递1更清楚地传递ExampleClass :: EXAMPLE_CONST_1但是这是传递常量的唯一原因?
To me its more clear to pass "ExampleClass::EXAMPLE_CONST_1" than to just pass "1", but it's that the only reason to pass constant?
推荐答案
简单地传递1不说太多。
Simply passing 1 doesn't say much. By having a constant you can have a description about the settings in the name.
例如:
constant RAIN = 1;
example: constant RAIN = 1;
方法setWeather(RAIN);
method setWeather(RAIN);
至少这是我使用它的方式和原因。
Atleast that's how and why I use it.
这篇关于为什么/如何在函数中使用传递的常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!