This is a simple one, I hope. How do I check, in the following example, if a constant is already defined?
#this works var = var||1 puts var var = var||2 puts var #this doesn't CONST = CONST||1 puts CONST CONST = CONST||2 puts CONST => 1 1 uninitialized constant CONST (NameError)
Checking if a PHP Constant is Defined This can be achieved using the PHP defined() function. The defined() function takes the name of the constant to be checked as an argument and returns a value of true or false to indicate whether that constant exists.
Definition and Usage The define() function defines a constant. Constants are much like variables, except for the following differences: A constant's value cannot be changed after it is set. Constant names do not need a leading dollar sign ($) Constants can be accessed regardless of scope.
No, you cannot redefine a constant (except with runkit_constant_redefine), that's why is called CONSTANT.
The basic difference between these two is that const defines constants at compile time, whereas define() defines them at run time. We can't use the const keyword to declare constant in conditional blocks, while with define() we can achieve that.
CONST = 2 unless defined? CONST
See here for more about awesome defined?
operator.
P.S. And in the future I guess you'll want var ||= 1
instead of var = var||1
.
const_defined? API
pry> User.const_defined?("PER_PAGE") => true pry> User.const_defined?("PER_PAGE123") => false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With