简体   繁体   中英

Does ColdFusion support type hinting?

In PHP I can do: $var = (int) $_POST['var'];

Is there a way to explicitly set a ColdFusion variable to an integer or a string?

Variables are typeless in CF. Although if you want to evaluate a variable as either a number or string, you could do:

#Val(<variable>)# 

and for strings

#ToString(<variable>)#

Depending on what you want to happen for data that can't be converted, maybe you want cfparam?

<cfparam name="form.v" type="numeric"/>

That will throw an exception if form.v is not present or is not numeric.

You can also test whether a value is numeric (or any other type):

<cfif isNumeric(form.v)>

and you can 'convert' a string a numeric value:

<cfset v = val(form.v) />

In addition to the good information in the other answers, it's worth mentioning that you can use isvalid() to see if a typeless value matches a bunch of different criteria:

isvalid('integer',x);
isvalid('float',x);
isvalid('string',x);

...etc. There are also some higher-level ones, like:

isvalid('email',x);
isvalid('telephone',x);

There are times when you must coerce a typeless value into a "true" type -- for instance, when you want to pass an argument to a Java method with more than one signature. You'd use javacast() , like so:

x = "01";
myJavaFunc.doSomething( x ); // ambiguous -- could be a string or number
myJavaFunc.doSomething( javacast('int', x ) ); // does something
myJavaFunc.doSomething( javacast('string', x ) ); // does something else

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM