Undefined variable in foreach loop - php

When I do a foreach() loop, the current array element's value $recipient is not defined on the line ->to($recipient). Why is this?
PHP Code (throws error)
foreach($recipients as $recipient) {
Mail::send('emails.invite', $data, function($m){
$m
->from('welcome#website.com', Auth::user()->name)
->to($recipient)
->subject('Auth::user()->name has invited you!');
});
}
Error
Notice: Undefined variable: recipient
PHP Code (NO error)
foreach($recipients as $recipient) {
echo $recipient;
}

You missed the use keyword. Change the code to :
foreach($recipients as $recipient) {
Mail::send('emails.shareListing', $data, function($m) use($recipient) {
$m
->from('share#asd.com', Auth::user()->name)
->to($recipient)
->subject('Auth::user()->name has shared a listing with you!');
});
}
See this documentation - especially the third example. Quote:
Closures may also inherit variables from the parent scope. Any such variables must be declared in the function header.

It's because you're inside the scope of the function.
Assuming you're using the PEAR package here, I don't understand why you're passing a function at all: http://pear.php.net/manual/en/package.mail.mail.send.php
If you meant to be doing this, you can use the use keyword to pass the variable into the function scope:
function($m) use($recipient) {

Related

OctoberCMS - Mail::send(), Undefined variables - Laravel

I am trying to send the SAME email to multiple addresses given from an array $emails.
I created a class called SendMail, and inside is a sendPost() method that accepts 2 arguments:
($post, $emails)
Here is my code:
class SendMail {
public static function sendPost($post, $emails)
{
Mail::send('acme.blog::mail.message', $post, function($message) {
$message->to($emails);
$message->from('mail#compuflexcorp.com', 'Compuflex Mail');
$message->subject($post['subject']);
$message->replyTo($post['email']);
});
}
}
The problem is, I keep receiving an error:
"Undefined variable $emails" on Line 14 of C:\...\SendMail.php
Line 14: $message->to($emails);
What I have tried:
I checked to see if I can access the $post and $emails variables inside of sendPost(), but outside of Mail::send(). And the answer is YES, I can access the information inside of $post and $emails inside of sendPost(), so the variables are, in fact, being passed to the sendPost() method.
I, at first, thought it had something to do with the fact that $emails is not one of the arguments for Mail::send(), so I put $post and $emails into one array called $vars, but then I got the error:
"Undefined variable $vars" on Line 14 of C:\...\SendMail.php
So, I realized that the issue seems to be that I can't pass any variables to Mail::send(), or in other words, I just don't know how to...
Any help would be greatly appreciated...
Thomas Yamakaitis
You need to pass the $emails variable as follows:
class SendMail {
public static function sendPost($post, $emails)
{
Mail::send('acme.blog::mail.message', $post, function($message) use ($emails) {
$message->to($emails);
$message->from('mail#compuflexcorp.com', 'Compuflex Mail');
$message->subject($post['subject']);
$message->replyTo($post['email']);
});
}
}

How to define function name using variable?

how to define function name (in PHP) using variable, like this?
$a='myFuncion';
function $a() {.......}
or like that?
The only way I know to give a fixed name to a function is to use eval, which I would not suggest.
More likely, what you want is to stuff a function IN a variable, and then just call that.
Try this:
$a = function() {
echo 'This is called an anonymous function.';
}
$a();
EDIT:
If you want to be accessible from other files, then use GLOBAL variable:
$GLOBALS['variable_name'] = 'my_func_123';
${$GLOBALS['variable_name']} = function() {
echo 'This is called an anonymous function.';
};
// Executing my_func_123()
${$GLOBALS['variable_name']}();
See also: http://php.net/manual/en/functions.anonymous.php

Undefined variable: _GET

I am having a problem with PHP that's confusing to me
Namely: Notice: Undefined variable: _GET in /var/www/dd.lo/app/libraries/system/input.php on line 86
pops up when you call:
$this->input->get('test');
The function calls another function (If my approach is bad please do not be mad. I will be happy if you tell me how to do it correctly):
public function get ($index)
{
return $this->_getArray('_GET', $index);
}
here is the code of the private function:
private function _getArray ($array, $index)
{
if (isset(${$array}[$index]))
{
return ${$array}[$index];
}
else
{
return NULL;
}
}
The Input class provides convenient access to _POST, _GET, _COOKIE and _SERVER data and allows you to avoid type checking:
if (isset($_POST['name']))
{
$name = $_POST['name'];
}
else
{
$name = NULL;
}
Incidentally, it requests a page at http://dd.lo/?test=dgdsgsdgsdgsd (i.e. $_GET, I asked)
If you write var_dump($_GET); then there is the index 'test'.
Apologies for the English, but I don't speak or read your language (Russian?). This answer is based on Google translate's version of what you asked.
PHP's super globals ($_GET, $_POST, etc.) are special variables, and it looks like you can't use these variables with PHP's variable variable feature. For example, this works
$foo = ['Hello'];
$var_name = 'foo';
var_dump($$var_name);
The "variable variable" $$var_name expands as $'foo'/$foo, and the variable dumps correctly.
However, the following does not work
$var_name = '_GET';
var_dump($$var_name);
It appears that whatever magic scope variable variables live in, that scope doesn't include the super globals. You'll need to rethink your approach. One way you might do this is by accepting the actual array instead of a string that's it's name, and specifying a "by reference" parameter in your function to avoid any performance issues
function _getArray(&$array, $key)
{
if(!is_array($array)) { throw new Exception("Invalid argumnet!");}
if(array_key_exists($key, $array))
{
return $array[$key];
}
return NULL;
}

php variable not detected

im having trouble with my php program, it seems that my array variable being declared earlier wasn't detected in a function. Here's my code :
$msg = array(
//Errors List
'Error1' => 'Error 1',
'Error2' => 'Error 2'
);
//Class for outputting Messages
class Message {
static function Info($string) { echo $string; }
static function Error($string) { echo $string; }
}
//Functions
function function1($var1) {
if (!preg_match("/^[0-9]+$/", $var1)){
Message::Error($msg['Error1']);
}
when i run it, and example i test the program like this..
$test = 'blabla';
function1($test);
it says the msg variable was undefined. Can anyone tell me how to resolve this?
Thanks in advance.
There are three ways to solve this issue.
Passing the required global var as a parameter
In my opinion, this is the preferred solution, as it avoids the pollution of your function with global variables. Global variables tend to introduce unexpected side effects and make maintenance and reuse of code a lot harder. A very extensive article on why you should avoid globals whenever possible (and some alternative solutions) can be found in the c2 wiki
function function1($var1,$mesg) {
if (!preg_match("/^[0-9]+$/", $var1)){
Message::Error($mesg['Error1']);
}
}
The call to function1 changes to
function1($test,$msg);
Using global:
Same effect as the one just below, other notation.
function function1($var1) {
global $msg;
if (!preg_match("/^[0-9]+$/", $var1)){
Message::Error($msg['Error1']);
}
}
Using the $GLOBALS superglobal
Some sources say this form is slightly faster than the one using global
function function1($var1) {
if (!preg_match("/^[0-9]+$/", $var1)){
Message::Error($GLOBALS['msg']['Error1']);
}
}
you can not use $msg as a local variable in function.
function function1($var1) {
global $msg;
if (!preg_match("/^[0-9]+$/", $var1)){
Message::Error($msg['Error1']);
}
}

Getting 'Fatal error: Call to undefined function' when using a function inside an if statement?

Ok, so I just finished off a function for validating the firstname field on a form.
This function works correctly on its own.
But since I want to make this function re-usable for more than one website, I added an if statement for whether or not to use it. The following code explain this:
Related PHP code:
//Specify what form elements need validating:
$validateFirstname = true;
//array to store error messages
$mistakes = array();
if ($validateFirstname=true) {
//Call first name validation function
$firstname = '';
if (!empty($_POST['firstname'])) {
$firstname = mysql_real_escape_string(stripslashes(trim($_POST['firstname'])));
}
$firstname = validFirstname($firstname);
if ($firstname === '') {
$mistakes[] = 'Your first name is either empty or Enter only ALPHABET characters.';
}
function validFirstname($firstname) {
if (!ctype_alpha(str_replace(' ', '', $firstname))) {
return '';
} else {
return $firstname;
}
}
}
So without this if ($validateFirstname=true) the code runs fine, but the moment I add it; I get the following error message:
Fatal error: Call to undefined function validFirstname()
Are you not able to use functions in if statements at all in PHP? I'm fairly new to using them in this way.
Conditional functions (functions defined inside the conditions) must be defined before they are referred. Here's what manual says:
Functions need not be defined before they are referenced, except when
a function is conditionally defined as shown in the two examples
below.
When a function is defined in a conditional manner such as the two
examples shown. Its definition must be processed prior to being
called.
So if you want to use it that way, you should put it either at the beginning of the if condition or outside the condition.
// Either:
if ($validateFirstname==true) {
function validFirstname($firstname) {}
}
// Or, and I'd rather do it this way, because function is
// created during "compilation" phase
function validFirstname($firstname) {}
if ($validateFirstname==true) {
// ...
}
Also not that function (even if created inside the condition) is pushed to global scope:
All functions and classes in PHP have the global scope - they can be called outside a function even if they were defined inside and vice versa.
So once code is evaluated it doesn't matter if it's declared inside condition or intentionally in global scope.
Functions that are declared in a conditional context (like if body), you can only use after their declaration.
if ($validateFirstname == true) {
//Call first name validation function
function validFirstname($firstname) {
// function body
}
// $firstname initialisation
$firstname = validFirstname($firstname);
// ...
}
(P.s.: changed $validateFirstname = true to $validateFirstname == true which should be what you want)
if($validateFirstname=true)
you are assigning the value "true" to $validateFirstname here
you should use a "==" for comparison e.g
if($validateFirstname==true)
that might help your "if" problem

Categories