I created a php function and I want to clear/reset the arguments of the function.
for example I've got this function declared twice in my index.php:
grid_init($type='portfolio',$postNb=4,$rowNb=2);
grid_init($type='post',$postNb,$rowNb);
function grid_init($type,$postNb,$rowNb) {
?>
<div class="container" data-type="<?php echo $type; ?>" data-postNb="<?php echo $rowNb; ?>" data-rowNb="<?php echo $rowNb; ?>">
some stuff.....
</div>
<?php
}
If I didn't specified my argument in my second function (in the above example $postNb $rowNb), these vars will take the values of the previous argument declared in the previous function ($postNb=4,$rowNb=2)...
How can I reset/clear my argument in my function between each function declared in a same file?
To make a function have default arguments it's like:
function grid_init($type, $postNb = 2, $rowNb = 4){
echo "<div class='container' data-type='$type' data-postNb='$rowNb' data-rowNb='$rowNb'>".
"some stuff.....".
'</div>';
}
Execute like:
grid_init('whatever'); // will assume $postNb = 2 and $rowNb = 4;
grid_init('some_data_type', 42, 11); // overwrite your defaults
You seem to have trouble calling functions.
Change your calls to
grid_init('portfolio',4,2);
grid_init('post','',''); // or use '' as default
a) you might have declared a function like this
function grid_init($type, $postNb, $rowNb)
{
// do stuff on $tyoe, $postNb, $rowNb
}
b) you might call the function several times, each time with new parameters
grid_init('post', 5, 4);
grid_init('somewhere', 1, 2);
A function does not memorize values of prior calls.
If you want that, then save them somewhere from within that function.
c) you might use default parameters on your function
Default parameters always come last in the function declaration.
function grid_init($type, $postNb = 2, $rowNb = 2)
{
// do stuff on $tyoe, $postNb, $rowNb
}
call it
grid_init('somewhere');
now postNb, rowNb are not set, but the default values from the declaration are used.
d) keep the number of parameters low!
Related
I'm having difficulty passing some variables from one function to another.
I've tried to make them global with little success.
The variables I would like to pass are the ones from send_email_notifications to send_email_notification_function.
function send_email_notifications($ID, $post) {
global $notificationTitle;
global $notificationPermalink;
$notificationTitle = $post->post_title;
$notificationPermalink = get_permalink($ID);
if(isset($_REQUEST['send_email_notification'])) {
date_default_timezone_set('Europe/London');
wp_schedule_single_event(time() + 10, 'send_email_notification_function_execute');
}
}
add_action('publish_Test_notifications', 'send_email_notifications', 10, 2);
function send_email_notification_function() {
global $notificationTitle;
global $notificationPermalink;
echo $notificationTitle;
echo $notificationPermalink;
$notificationEmail = 'test#test.com';
wp_mail($notificationEmail, $notificationSubject, $notificationContent);
}
add_action('send_email_notification_function_execute', 'send_email_notification_function');
It seems you are using wordpress. Your question might be better answered on https://wordpress.stackexchange.com/.
You should use an object instead of a function for the callable parameter of add_action. Your object can contain your global variables.
For example you can create a php class called EmailNotification and it can have two functions send_email_notification_function and send_email_notifications. This class can have two properties called $notificationTitle and $notificationPermalink.
You can then create an instance of this class and use it as the second argument to add_action.
I'm trying to write a simple function which takes two arguments, adds them together and returns the result of the calculation.
Before performing the calculation the function checks whether either of the two arguments are undefined and if so, sets the argument to 0.
Here's my function:
Function - PHP
function returnZeroAdd ($arg, $arg2)
{
if(!isset($arg))
{
$arg = 0;
}
if(!isset($arg2))
{
$arg2 = 0;
}
echo $arg + $arg2;
}
I've tried to execute it like so :
returnZeroAdd($bawtryReturnCount, $bawtryFReturnCount);
But this throws up an undefined variable $bawtryFReturnCount error.
I do not know why the function isn't setting $bawtryFReturnCount) to 0 before performing the calculation thereby negating the 'undefined variable' error.
Can anybody provide a solution?
You cannot do this the way you want. As soon as you use an undefined variable, you will get this error. So the error doesn't occur inside your function, but already occurs in the call to your function.
1. Optional parameters
You might make a parameter optional, like so:
function returnZeroAdd ($arg = 0, $arg2 = 0)
{
return $arg + $arg2;
}
This way, the parameter is optional, and you can call the function like this:
echo returnZeroAdd(); // 0
echo returnZeroAdd(1); // 1
echo returnZeroAdd(1, 1); // 2
2. By reference
But I'm not sure if that is what you want. This call will still fail:
echo returnZeroAdd($undefinedVariable);
That can be solved by passing the variables by reference. You can then check if the values are set and if so, use them in the addition.
<?php
function returnZeroAdd (&$arg, &$arg2)
{
$result = 0;
if(isset($arg))
{
$result += $arg;
}
if(isset($arg2))
{
$result += $arg2;
}
return $result;
}
echo returnZeroAdd($x, $y);
Note that you will actually change the original value of a by reference parameter, if you change it in the function. That's why I changed the code in such a way that the parameters themselves are not modified. Look at this simplified example to see what I mean:
<?php
function example(&$arg)
{
if(!isset($arg))
{
$arg = 0;
}
return $arg;
}
echo example($x); // 0
echo $x // also 0
Of course that might be your intention. If so, you can safely set $arg and $arg2 to 0 inside the function.
The error is not thrown by the function itself, as the function is not aware of the global scope. The error is thrown before even the function is executed, while the PHP interperter is trying to pass $bawtryFReturnCount to the function, one does not find it, and throws error, however, it's not a fatal one and the execution is not stopped. THerefore, the function is executed with a non-set variable with default value of null, where I guess, isset will not work, as the arguments are mandatory, but not optional. A better check here will be empty($arg), however the error will still be present.
Because the functions are not and SHOULD NOT be aware of the global state of your application, you should do these checks from outside the functions and then call it.
if (!isset($bawtryReturnCount)) {
$bawtryReturnCount = 0
}
returnZeroAdd($bawtryReturnCount);
Or assign default values to the arguments in the function, making them optional instead of mandatory.
Your function could be rewritten as:
function returnZeroAdd ($arg = 0, $arg2 = 0)
{
echo $arg + $arg2;
}
You missunderstand how variables work. Since $bawtryFReturnCount isn't defined when you call the function; you get a warning. Your isset-checks performs the checks too late. Example:
$bawtryReturnCount = 4;
$bawtryFReturnCount = 0;
returnZeroAdd($bawtryReturnCount, $bawtryFReturnCount);
Will not result in an error.
If you really want to make the check inside the function you could pass the arguments by reference:
function returnZeroAdd (&$arg, &$arg2)
{
if(!isset($arg))
{
$arg = 0;
}
if(!isset($arg2))
{
$arg2 = 0;
}
echo $arg + $arg2;
}
However this will potentially modify your arguments outside the function, if it is not what you intend to do then you need this:
function returnZeroAdd (&$arg, &$arg2)
{
if(!isset($arg))
{
$localArg = 0;
}
else
{
$localArg = $arg;
}
if(!isset($arg2))
{
$localArg2 = 0;
}
else
{
$localArg2 = $arg2;
}
echo $localArg + $localArg2;
}
You can now pass undefined variables, it won't throw any error.
Alternatively you might want to give a default value to your arguments (in your case 0 seems appropriate):
function returnZeroAdd ($arg = 0, $arg2 = 0)
{
echo $arg + $arg2;
}
You have to define the variable before pass it to an function. for example
$bawtryReturnCount=10;
$bawtryFReturnCount=5;
define the two variable with some value and pass it to that function.
function returnZeroAdd ($arg=0, $arg2=0)
{
echo $arg + $arg2;
}
if you define a function like this means the function takes default value as 0 if the argument is not passed.
for example you can call the functio like this
returnZeroadd();// print 0
returnZeroadd(4);// print 4
returnZeroadd(4,5);// print 9
or you can define two variables and pass it as an argument and call like this.
$bawtryReturnCount=10;
$bawtryFReturnCount=5;
returnZeroadd($bawtryReturnCount, $bawtryFReturnCount);
How would I alter the function below to produce a new variable for use outside of the function?
PHP Function
function sizeShown ($size)
{
// *** Continental Adult Sizes ***
if (strpos($size, 'continental-')!== false)
{
$size = preg_replace("/\D+/", '', $size);
$searchsize = 'quantity_c_size_' . $size;
}
return $searchsize;
Example
<?php
sizeShown($size);
$searchsize;
?>
This currently produces a null value and Notice: undefined variable.
So the function takes one argument, a variable containing a string relating to size. It checks the variable for the string 'continental-', if found it trims the string of everything except the numbers. A new variable $searchsize is created which appends 'quantity_c_size_' to the value stored in $size.
So the result would be like so ... quantity_c_size_45
I want to be able to call $searchsize outside of the function within the same script.
Can anybody provide a solution?
Thanks.
Try using the global keyword, like so:
function test () {
global $test_var;
$test_var = 'Hello World!';
}
test();
echo $test_var;
However, this is usually not a good coding practice. So I would suggest the following:
function test () {
return 'Hello World!';
}
$test_var = test();
echo $test_var;
In the function 'sizeShown' you are just returning the function. You forgot to echo the function when you call your function.
echo sizeShown($size);
echo $searchsize;
?>
But the way you call $searchsize is not possible.
This is an old question, and I might not be understanding the OP's question properly, but why couldn't you just do this:
<?php
$searchsize = sizeShown($size);
?>
You're already returning $searchsize from the sizeShown method. So if you simply assign the result of the function to the $sizeShown variable, you should have what you want.
In codeigniter what is the correct method of passing variables to the callback function?
I have used this,
$var1 = 'some conditions';
$this->form_validation->set_rules("callback__is_value_unique[value, $var1]");
public function _is_value_unique($value, $var1){
echo $var1;
die;
}
This gave me output like shown below:-
value, some conditions
rather than,
some conditions
You must only set your value!
$var1 = 'some conditions';
$this->form_validation->set_rules("callback__is_value_unique[value, $var1]");
public function _is_value_unique($value, $var1){
echo $var1;
die;
}
From the docs..
If you need to receive an extra parameter in your callback function,
just add it normally after the function name between square brackets,
as in: "callback_foo[bar]", then it will be passed as the second
argument of your callback function.
Sounds like you could only pass one extra argument. Which should be a string. If you want to pass more arguments, you could store them somewhere else and just pass an argument, which stores the location of the additional param.
$index = count($this->arguments);
$this->arguments[$index] = array('value', 'some conditions'/*, ...*/);
$this->form_validation->set_rules("callback__is_value_unique[$index]");
public function _is_value_unique($value, $index){
$args = $this->argumts[$index];
echo $args[1];
die;
}
I want to use a function to echo a value I named, "name". The value is sent to the function via the POST method from a form.
My HTML:
<html>
<head>
<title> function play </title>
</head>
<body>
<form method="post" action="function.php">
Name: <input type="text" name="name"/>
<input type="submit" name="submit" value="submit"/>
</form>
</body>
</html>
My PHP:
<?php
$name= $_POST['name'];
function writeName($name)
{
echo $name;
}
writeName();
?>
For some reason I keep getting the error:
Warning: Missing argument 1 for writeName(), called in C:\xampp\htdocs\function.php on line 7 and defined in C:\xampp\htdocs\function.php on line 3
Notice: Undefined variable: name in C:\xampp\htdocs\function.php on line 5
What am I doing wrong?
You need to pass a parameter in to the function.
writeName($name);
As others have said, you need to pass your value as as an argument when you call the function.
Variables in PHP are "scoped". This means that wherever you define your variable will affect its context. In your example, $name defined at the script level is not the same as $name defined as a function parameter. However, $name used within your function will always refer to the same variable within that function.
To put that in practice, consider the following:
$name = 'a';
function writeName( $name )
{
echo $name; // echoes 'b'
}
writeName( 'b' );
echo $name; //echoes 'a'
Another way to think about it is by just changing the names of the variables so they are noticeably different:
$getName= $_POST[ 'name' ];
function writeName( $nameToWrite )
{
echo $nameToWrite;
}
writeName( $getName );
You can also use the global keyword inside your function to let PHP know that you're referencing a variable in the global scope (i.e., at the script level, outside your function) but this is generally bad practice.
$getName = $_POST[ 'name' ];
function writeName() // Notice that we don't need to pass $getName as an argument
{
global $getName;
echo $getName;
}
writeName();
You defined your function as function writeName($name), which means it's expecting an argument. But when you call the function, you don't pass an argument. Try changing
writeName();
to:
writeName($name);
You have to pass a parameter to the function writeName($name);
or you can set a default for the function parameter:
function writeName($name = null)
{
echo $name;
}
You're not passing the parameter to the function. Try this:
<?php
function writeName($name)
{
echo $name;
}
writeName($_POST['name']);
?>
The reason is: you declared your writeName function as expecting an argument called $name. But when you call the function, you are not passing any parameters. You should use the function like this:
writeName("some string here");
You've defined your 'writeName' function to accept one parameter. When calling the function you must provide this parameter.
writeName($name);
or
writeName($_POST['name']);