Check if a function is called with parameters - php

Codeigniter has a syntax for url parameter passing for functions inside the controller.
If a function for example:
function index($id){
$this->model->get_user($id);
}
Assuming that this function is called without supplying the ID namely called as
ProjectName/Controller/index
it will return an error as it expects a parameter.
Is there a way to check if a parameter exists.

No there is not a way to check if one exists per-say as that error happens before the controller has a chance to run code. ie. before the class method executes.
That said there is a simple workaround for this: You can supply a default value and check for that for example
function index($id = null){
if( is_null($id) ){
///do something - like show a pretty error, or redirect etc...
}else{
$this->model->get_user($id);
}
}
This way when no parameter is supplied the ID will be null, this is fairly safe ( when using null ) because you can never supply null as part of the url path even doing this
www.mysite.com/index/null //or however the url works out in your case
Will supply null as a string, because everything in the url comes through as a string. So 'null' as a string is not in fact null it's just the word null. If that makes sense. So given that null could never be supplied and only happens if no other value is supplied.
In this case it may be worth casting the input to a int or further checking if it's an improper value.
This could be done several ways:
Casting:
function index($id = null){
if( is_null($id) ){
///do something - like show a pretty error, or redirect etc...
}else{
$this->model->get_user((int)$id);
//cast to int, things that are not INT or string equivalents become 0, which should not find a user as it would look for ID = 0
}
}
By Regx check:
function index($id = null){
if( is_null($id) ){
///do something - like show a pretty error, or redirect etc...
}else if( preg_match('/^[^\d]+$/', $id )){
// not an int ( contains anything other than a digit )
}else{
$this->model->get_user($id);
}
}
Cheers.

Related

Undefining a variable set as a default value in a function argument list PHP

EDIT: I want the default value of the argument to a function as undefined, so that when there is no argument passed to the function the return value of isset($argument) is equals to TRUE
I am not sure if I know the correct nomenclature, but what I need to do is this inside a class :
public function something ( $myvariable = unset ($myvariable) ){
if ( isSet ( $myvariable ) ) //do something
else //do something else
}
I know I can check for null if I set it like $myvariable = NULL, but I want to keep the coding style constant through out the website if possible.
How do I do it ?

Value of option arguments: FALSE or NULL

When you have optional arguments that can have different types, which value is most suited to point out that the argument should not be taken into consideration? False or Null?
null is the value used to represent "no value", whereas false means "no", "bad", "unsuccessful", "don't" etc.
Therefore: null.
For me this depends on what I'm going to do with the value of said argument...
I am writing a database function where I can have default values as NULL
function somedbfunc($id = NULL, $column1 = NULL)
If these values are null my function may insert a blank record..
If I need to stop my function because of a non argument I may use FALSE
function blah($this = FALSE, $that = FALSE)
{
if ( ! $this || ! $that)
{
return FALSE;
....
So I am saying that both are totally valid, but it depends on the situation you find yourself in.
For optional arguments use null (generally).
Use null, if you need to differentiate between boolean values (true/false) and nothing (null). On the other hand if you don't need to check for not-set argument and you are using boolean variable then I'd go for false.
As you are saying that you want to tell the "optional arguments" "not be taken into consideration", I will go for null. False is explicitly saying "no" to the recipient. which is a valid input.

Joomla: Passing a variable into getInput()

I'm building a backend component (1.6 / 1.7 / 2.5) where I need to pass a variable from another view into a field in a new record. Variable passing is working fine.
My problem is using getInput().
To start with different doc pages have different amounts and formatting of parameters - confusing! For example:
http://docs.joomla.org/API16:JForm/getInput: getInput($name, $group= '_default', $formControl= '_default', $groupControl= '_default', $value=null)
vs
http://docs.joomla.org/JForm::getInput/1.6:
public function getInput (
$name
$group=null
$value=null
)
The problem:
I just need to pass a variable as a default value, something like:
echo $this->form->getInput('id', $value=$this->userID );?>
The above code makes the input field disappear. If I take out the $value=$this->userID the input field shows up though obviously doesn't have any default value. I've also tried:
$value=$this->userID;
echo $this->form->getInput('id', $value );
And same problem, the input field goes away. I tried a few other variations but basically if I try to put anything else within getInput() it doesn't work nor can I find any good working examples of how to use these other parameters.
What am I doing wrong?
Thanks!
According to the source, this is the correct API:
getInput($name, $group = null, $value = null)
And getInput() just calls getField():
getField($name, $group = null, $value = null)
Which means you should be doing this to set a default value:
echo $this->form->getInput('id', null, $this->userID ); // Returns the $field->input String
Or:
$field = $this->form->getField('id', null, $this->userID ); // Returns the JFormField object

How can I call a function specified in a GET param?

I have a simple link like so: Accept
The idea is that this will run a function called wp_accept_function and pass in the id of 10 how do I do this? Thanks
Here is the code I have so far, but I feel I'm going wrong and need to pass the number into the function and then be able to use it within the function. Thanks
if ( isset ( $_GET ['wp_accept_function'] ) )
{
function wp_accept_favor ( $id )
{
// JAZZ
}
}
I think you want this:
First you need to define the function.
function wp_accept_favor($id) {
// do something
}
Then, you have to check if the parameter is set and call the function.
if (isset($_GET['wp_accept_function'])) {
// call the function passing the id casted to an integer
wp_accept_favor((int)$_GET['wp_accept_function']);
}
The cast to (int) is for avoid passing a non-integer type for wp_accept_favor() function, but you can handle it as you want.
If you are trying to build something generic...
// Add a white list of functions here which can be called via GET.
$safeFunctions = array('wp_accept_function');
foreach($_GET as $function => $argument) {
if (in_array($function, $safeFunctions)
AND function_exists($function)) {
$function($argument);
}
}
However, make sure you have a whitelist of safe functions, otherwise your app will no doubt have security issues.

How to pass specific variable in PHP function

I have a PHP function that requires can take 3 parameteres... I want to pass it a value for the 1st and 3rd parameters but I want the 2nd one to default...
How can I specify which ones I am passing, otherwise its interpreted as me passing values for the 1st and 2nd slots.
Thanks.
You cannot "not pass" a parameter that's not at the end of the parameters list :
if you want to specify the 3rd parameter, you have to pass the 1st and 2nd ones
if you want to specify the 2nd parameter, you have to pass the 1st one -- but the 3rd can be left out, if optionnal.
In your case, you have to pass a value for the 2nd parameter -- the default one, ideally ; which, yes, requires your to know that default value.
A possible alternative would be not have your function take 3 parameters, but only one, an array :
function my_function(array $params = array()) {
// if set, use $params['first']
// if set, use $params['third']
// ...
}
And call that function like this :
my_function(array(
'first' => 'plop',
'third' => 'glop'
));
This would allow you to :
accept any number of parameters
all of which could be optionnal
But :
your code would be less easy to understand, and the documentation would be less useful : no named parameters
your IDE would not be able to give you hints on which parameters the function accepts
Once you've defined a default parameter, all the parameters after that one cannot be required. You could do something like:
const MY_FUNCTION_DEFAULT = "default";
public function myFunction($one, $two = "default", $three = 3)
{
if (is_null($two)) $two = self::MY_FUNCTION_DEFAULT;
//...
}
// call
$this->myFunction(1, null, 3);
You might also define an empty parameter set and use func_get_args to pull in parameters and analyze those using instanceof or typeof/gettype for type checking if your function is simple enough.
You could use ReflectionFunction. This problem has already been solved by an anonymous contributor at php.net, see orinal here: http://www.php.net/manual/en/function.call-user-func-array.php#66121
For those wishing to implement call-by-name functionality in PHP, such as implemented e.g. in DB apis, here's a quick-n-dirty version for PHP 5 and up
function call_user_func_named($function, $params)
{
// make sure we do not throw exception if function not found: raise error instead...
// (oh boy, we do like php 4 better than 5, don't we...)
if (!function_exists($function))
{
trigger_error('call to unexisting function '.$function, E_USER_ERROR);
return NULL;
}
$reflect = new ReflectionFunction($function);
$real_params = array();
foreach ($reflect->getParameters() as $i => $param)
{
$pname = $param->getName();
if ($param->isPassedByReference())
{
/// #todo shall we raise some warning?
}
if (array_key_exists($pname, $params))
{
$real_params[] = $params[$pname];
}
else if ($param->isDefaultValueAvailable()) {
$real_params[] = $param->getDefaultValue();
}
else
{
// missing required parameter: mark an error and exit
//return new Exception('call to '.$function.' missing parameter nr. '.$i+1);
trigger_error(sprintf('call to %s missing parameter nr. %d', $function, $i+1), E_USER_ERROR);
return NULL;
}
}
return call_user_func_array($function, $real_params);
}
function ($foo, $mate, $bar = "") {
// ... some code
}

Categories