zephir
zephir copied to clipboard
Boolean variable casting from different type
Request enhancement (since it's not an official feature in the documentation)
One syntax that we use a lot daily in development :
string str = "abc";
boolean test = !!str;
boolean test2 = !str;
One is a boolean cast. Other is to check for not empty value ("0" included).
The compiler will throw the following error : Unknown type: string in ...
I believe other types other than string will not work too.
Note that the following syntax will work : if !str { ... } but not if !str || str === null {...} because || and && are not accepted after a string even thought it's type casted with !
Why do we need this? Because we don't want to bother to write everytime
str !== "" && str !== null && str !== 0 && str !== "0" && str !== false && str !== []
Well, how about empty(str) ?
That could work. Still !! is preferred over empty(empty()). It's also a C implementation.
Also when we use an external function in zephir, the compiler force us to use a var type variable
Returned values by functions can only be assigned to variant variables
Would be nice to do a cast
var bool;
let bool = (boolean) externalFunction(); //or use !!
or direct implementation
boolean bool;
let bool = externalFunction();
The aim of zephir is to achieve the maximum speed so little details for the compiler to optimize are important.
We can also implement a "header" for zephir for hinting. Ex: functions.zh (as Zephir header)
externalFunction(string arg1) -> boolean;
Classname::externalFunction2(object arg1) -> Closure;
Method header inside the same class or within the Zephir land should be recognized automatically.
I have find a solution for this,may be it not the best but working for me for php extension.
I am taking all my boolean variable as var and then using regex for checking it.
var status; //define
if preg_match("/^[0,1]{1}$/", status)
{
// your code goes here.. only will pass 0 or 1
}
Two things about your regex. One, the {1} is superfluous - regular expressions already match only a single character (well, byte, in this case) unless told to match more. If you like it for clarity, that's fine, but it doesn't do anything functional at all. Second, though, is more important. The , in your [] character set doesn't have a syntactical purpose - it will be matched literally, meaning the strings 0, 1, and , will all match. You probably want to remove that.
I'm also not sure it actually addresses the original use case, and the overhead of compiling and evaluating a regular expression... It's not the greatest, as you said. 😅