Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
function myCheck($in)
{ return isset($in); }
$var1='Something';
$var2='$var1';
$var3='$varNonExitant';
What I'm trying to achive is to use myCheck to evaluate the existance of the content like this:
myCheck($var2) return true;
myCheck($var3) return false;
isset() is not really a function: it's a language construct. As such, it's allowed to do some magic that's not available to regular functions, such as being fed with non-existing variables.
To sum up: you cannot replicate it with a custom function.
Edit:
As DaveRandom pointed out in a comment below, all you can do is come close by checking if a variable isset for example:
function variable_isset(&$variable = NULL) {
return isset($variable);
}
This approach offers two drawbacks though:
This works by passing the unset variable by reference, thus creating it when called. As it's NULL it is still not set.
It'll trigger an Undefined variable notice if the variable does not exist, ruining the whole concept of gracefully handling optional variables.
Most likely this should not be needed. So question remains why you can not use isset in the first place which would be much more needed to give you better guidance.
When you cyall myCheck($abc), with set $abc = 123, it gets myCheck(123). It isn't any valid argument for isset.
You have to give the function a string with variable name:
function isset_global($variable_name)
{
return isset($GLOBALS[$variable_name]);
}
Of course, I am also wondering, why to do this, but it answers the question as long as you check a global variable.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
Hi my limited understanding of PHP the define() function redefines a variable to another correct?
So in the following function if the pointer to $default=='on' surely the return value would be true? Instead Im still getting 'on' returned. Thanks for forgiving my limited knowledge.
function isseter(&$default,&$reserve=NULL)
{
define('on',true,true);define('off',false,true);
if (isset($default)) return $default;
else return $reserve;
}
define doesn't redefine a variable. It defines a constant.
Basically, you could do something like
define('on', 'It is on');
which defines a constant on that you can use in the rest of your program, like this:
echo on // Output will be "It is on"
Notice that there is no dollar sign in front of the on since it is not a variable
You can modify your program to make it work like you want like this.
function isseter(&$default,&$reserve=NULL)
{
define('on',true,true);
if (isset($default)) return $default == on
else return $reserve;
}
This returns the boolean result of comparing the variable $default to the constant on, which is true. Although, once you define a constant, it is enabled for the rest of your program and not just inside that function. So usually you define constants in the beginning of your program. You can do this:
// Constants
define('on',true,true);
// Functions
function isseter(&$default,&$reserve=NULL)
{
if (isset($default)) return $default == on
else return $reserve;
}
// Rest of program
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I want to find how to get number of variables to be passed in function.
say suppose I have function
public function abc($id,$name,$email){
....
}
Now there is another function xyz in want to know number of variables that are need to be passed in this function.
Thanks in advance.
Now there is another function xyz in want to know number of variables that are need to be passed in this function.
Use this:
$rfunc = new ReflectionFunction('xyz');
echo $rfunc->getNumberOfRequiredParameters();
But I do not know for what this should be useful...
if you did not know how many number of variables that are need to be passed in calling function, then you can make use default value of parameter concept.
For ex:
// Function call-1
abc($a,$b,$c);
// Function call -2
abc($a,$b,$c,$d);
// Function defination goes here
function abc($a,$b,$c,$d=0)
{
/* if you did not pass $d value , $d gets assigned automatically to 0
as default value. So in this way, you should not be worried about how
many parameters you should pass */
}
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
In PHP, the following yields the same result:
function bla1() {
return null;
}
function bla2() {
// nothing happening here...
}
So if I do this:
$bla1 = bla1();
$bla2 = bla2();
In both cases the value of bla1 and bla2 is in fact NULL. So my question is, which is best practice? Bla1 is more code, but makes it more obvious what you are doing. But bla2 is less code and yields the same result. Which is better?
If the function is meant to return something, for example: either an object if it exists, or null if it doesn't, then make it explicit by returning null.
If the function is not meant to return something, then don't make it return null. You can have a single return statement on its own if you need to exit the function early.
In most software development projects , the 20-80 rules applies . You will spend 20% of the time on developing your software and 80% of the time maintaining the software. With this rule in mind , Code Readability becomes so important in helping you and your colleagues maintain the software .
If you choose
function bla2() //not advisable
{
// nothing happening here...
}
You will plant doubts into the mind of colleagues of what is the actual function of the code when they review the code at a later date
I would be explict and choose
function bla1() //advisable
{
return null;
}
If the function is tend to return data, then return data or null when there is nothing to return. If the function doesn't meant to return any data back, then return true or false depends on if the function was executed successfully or not.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
In some examples of PHP, I see people assign things to shorthand variables, and then use the shorthand variables instead. Is this common practice? Is this good practice?
$name = $_POST['name'];
and then they use they use $name down here to echo it or use it as a function parameter.
Another example is:
DEFINE('DB_USER', 'username');
mysqli_connect(DB_USER.......);
Pros:
Shorthand variables can be easier to type and remember.
A shorthand variable might allow an expensive operation to be done once instead of repeated many times. But beware of premature optimization! Most of the time this sort of optimization would be premature.
A shorthand variable can be used to make a copy that can be changed without modifying the original variable.
In some languages, a shorthand variable can be used to make a copy that is guaranteed to persist even if the the original variable is modified.
Cons:
Indiscriminate use of shorthand variables can result in multiple names for the same values.
In some languages and situations, a shorthand variable will make an unnecessary copy, using additional resources.
I have been doing php professionally for about 5 years now.
Usually when getting post variables it is a good idea, but even more common is to wrap it in an isset ternary if statement:
$name = isset($_POST['name']) ? $_POST['name'] : false;
This way if the variable isn't passed then you don't get an undefined variable warning.
Further, it saves you having to type $_POST every time, and it helps encapsulate the code a bit better.
The most important thing when writing code is writing readable code, not just for others but also for yourself. We do this all the time, i.e. abstracting and applying oo methods of programming.
So predefining the variables we'll be using and setting defaults makes perfect sense.
I would do something like this...
class ValueTooLong extends Exception {}
function R($param, $default=null, $type='string', $max_length=null) {
if(!isset($_REQUEST[$param]))
return $default;
$r = $_REQUEST[$param];
if($max_length && strlen($r) > $max_length)
throw new ValueTooLong('Length of '.$param.' was '.strlen($r).'. Max length is: '.$max_length);
if($type === 'bool' || $type === 'boolean') {
if($r === 'false' || $r === 'no')
return false;
return !empty($r);
}
settype($r, $type);
return $r;
}
# Which allows me do do this:
$name = R('name');
# or:
$count = R('count', 1, 'int');
EDIT: Function now takes a max_length parameter (as suggested by comment) and throws an exception if value of request parameter is too long
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
This is not a duplicate of "In PHP, how do I check if a function exists?".
http://us3.php.net/function_exists will fail if input is a language
construct (e.g. http://us1.php.net/empty).
http://us1.php.net/is_callable with $syntax_only = true will allow
language constructs (e.g. empty), though it will also allow
random_function_that_does_not_exist.
How do I check if input is callable, either as an existing function or a language construct that behaves like a function?
There are all kinds of potential problems with what you're asking. However if I understand you right, you simply want to know if somename can be called like somename('someinput').
If that's true, then it appears you need to use a combination of function_exists and a manual lookup of language constructs from the List of Keywords.
Something like this perhaps:
function canICall($function) {
$callableConstructs = array("empty","unset","eval","array","exit","isset","list");
return function_exists($function) || in_array($function, $callableConstructs);
}
That $callableConstructs array is not complete, look at the List of Keywords page to build it out.
Yes it is hackish, but without a built-in way to do this in PHP I don't see another option.
Note that just because you can call something like a function, does not make it a function, nor does it mean that it behaves like a function in other ways.
You cannot call it dynamically:
$var = "empty";
$var('someinput'); // Does NOT work
Nor does this work:
call_user_func('empty', $foo);
You could use it in an eval call, but I hope you understand the huge list of reasons why that can be dangerous.
Since empty always exists and is a language construct which cannot be called using variable functions, it doubly makes no sense to want to use function_exists on it. Even if function_exists would work, it is not possible to write this code:
$func = 'empty';
if (function_exists($func)) {
$func($var);
}
The only way to call empty() is to write it literally in your source code. You cannot call it using variable functions any more than you can do that with list() = or /.
The best you could do is:
if (function_exists('empty')) {
empty($foo);
}
But because empty always exists, what's the point in testing for it?
If you want to make a validation rule, simply write your own function:
function isEmpty($value) {
return !$value;
}
$rule = 'isEmpty';
This does exactly the same thing.
Or you make empty a special case in your rule execution:
function validate($rule, $value) {
switch ($rule) {
case 'empty' :
return !$value;
default :
if (!function_exists($rule)) {
throw new InvalidArgumentException("$rule does not exist");
}
return $rule($value);
}
}