PHP access variable from anonymous function [duplicate] - php

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Render a variable during creation of anonymous PHP function
I am still quite new with PHP and this bothers me:
class Controller {
...
...
function _activateCar() {
$car_id = $this->data['car']->getId();
// $car_id == 1
$active_car = array_filter($this->data['cars'], function($car){
// $car_id undefined
return $car->getId() == $car_id;
});
}
...
...
}
Why can't the function inside array_filter access the $car_id variable? Keeps saying undefined.
Is there an other way to make $car_id accessible than to make a $_GET['car_id'] = $car_id;? Using the global keyword didn't help.

You need to add use($car_id) to your anonymous function, like so:
$active_car = array_filter($this->data['cars'], function($car) use($car_id){
// $car_id undefined
return $car->getId() == $car_id;
});

Anonymous functions can import select variables with the use keyword:
$active_car = array_fiter($this->data['cars'],function($car) use ($car_id) {
return $car->getId() == $car_id;
});

Related

PHP: use for loop/foreach inside array_filter [duplicate]

This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
How does 'function' and 'use' and 'array_filter' work in PHP?
(2 answers)
Closed 12 months ago.
I tried to use for-loop/foreach inside array_filter(). but the for loop/foreach doesn't work inside array_filter(). How can I use for-loop/foreach inside array_filter()?
$bookingData = array_values(array_filter($jsonBooking, function($bookingItem) {
foreach ($orderData as $orderItem) {
if ($bookingItem['order_id'] === $orderItem['id']) {
return $bookingItem;
}
}
}
Callback inside array_filter must returns bool (as condition to filter), be but you return an object.
This should work.
$bookingData = array_values(array_filter($jsonBooking, function($bookingItem) use ($orderData) {
foreach ($orderData as $orderItem) {
if ($bookingItem['order_id'] === $orderItem['id']) {
return true;
}
}
return false;
}
UPDATED: don't forget use statement

How do I extract the parameters in a function call from source code? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
PHP: Get name of variable passed as argument
How to get a variable name as a string in PHP?
If I have
$abc = '123';
function write($var){
}
How would I inside write find out that the variable now represented by $var was called $abc?
It's not possible. Even pass-by-reference won't help you. You'll have to pass the name as a second argument.
But what you have asked is most assuredly not a good solution to your problem.
You can not get the variable name, but if you want it for debugging, then you can use PHP's built-in debug_backtrace(), and I recommend to take a look on Xdebug as well.
With this function, you can get some data on the caller, including the file and line number, so you can look up that line manualy after running the script:
function debug_caller_data()
{
$backtrace = debug_backtrace();
if (count($backtrace) > 2)
return $backtrace[count($backtrace)-2];
elseif (count($backtrace) > 1)
return $backtrace[count($backtrace)-1];
else
return false;
}
Full example:
<?php
function debug_caller_data()
{
$backtrace = debug_backtrace();
if (count($backtrace) > 2)
return $backtrace[count($backtrace)-2];
elseif (count($backtrace) > 1)
return $backtrace[count($backtrace)-1];
else
return false;
}
function write($var)
{
var_dump(debug_caller_data());
}
function caller_function()
{
$abc = '123';
write($abc);
}
$abc = '123';
write($abc);
caller_function();

Function returns NULL instead of a value [duplicate]

This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
Closed 5 years ago.
I wrote a function that I thought cannot be more basic:
In functions.php:
function testowa() {
$stringToReturn = "pies";
return $stringToReturn;
}
Then I'm trying to call it in single.php:
include_once ('functions.php');
testowa();
var_dump($stringToReturn);
And var_dump displays NULL.
Where could I possibly do anything wrong?
You have to assign the function's response to a variable. Try
$stringToReturn = testowa();
var_dump($stringToReturn);
#MichaƂ Skrzypek update your function.php file like below:
<?php
function testowa() {
global $stringToReturn;
$stringToReturn = "pies";
return $stringToReturn;
}
Some ways to rome.
Return Value Version:
function testowa() {
return = "pies";
}
print testowa();
Reference Version
function testowa(&$refer) {
$refer = "pies";
}
$refer = '';
testowa($refer);
print $refer;
Global Version
function testowa() {
global $global;
$global = "pies";
}
$global='';
testowa();
print $global;
But take the Return Value Version and avoid Global Version

array_map in php with callback OOP [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to use an object method as a callback function
Usually I used array_map with procedural code, but in this case I'm working in OOP and the callback should be "this->id2areas", but It's not working. Is there anyway of put this callback with OOP?
ERROR MESSAGE: array_map() expects parameter 1 to be a valid callback, function 'this->id2area' not found or invalid function name
MY CODE
=================================================================================
$this->context->assign('user_areas', implode(', ', array_map('id2area', explode(',', $this->user['areas']))));
explode(',', $this->user['areas']))));
function id2area($id) {//callback
if ($id == 0) {
return 'National';
}
$query = "SELECT area FROM area WHERE id = $id";
return DB::fetch_instance()->slave->fetchColumn($query);
}
In PHP, you can use an array to associate an object and a method call as a callable
array_map(array($this, 'id2area'), $array);
http://php.net/manual/en/language.types.callable.php
PHP callbacks for objects is a bit different then global functions.
//Global function callback
array_map('id2area', $data);
// Object function
array_map(array($object, 'id2area'), $data)
// - or -
array_map(array($this, 'id2area'), $data)
// Static class function
array_map(array('Class_Name', 'id2area'), $data)
// - or -
array_map('Class_Name::id2area', $data)
http://us1.php.net/manual/en/language.types.callable.php
You could also do this as an anonymous function like:
array_map(
function($arg) {
return $this->id2area($arg);
},
explode(',', $this->user['areas'])
);

original variable name passed to function? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
PHP: Get name of variable passed as argument
How to get a variable name as a string in PHP?
If I have
$abc = '123';
function write($var){
}
How would I inside write find out that the variable now represented by $var was called $abc?
It's not possible. Even pass-by-reference won't help you. You'll have to pass the name as a second argument.
But what you have asked is most assuredly not a good solution to your problem.
You can not get the variable name, but if you want it for debugging, then you can use PHP's built-in debug_backtrace(), and I recommend to take a look on Xdebug as well.
With this function, you can get some data on the caller, including the file and line number, so you can look up that line manualy after running the script:
function debug_caller_data()
{
$backtrace = debug_backtrace();
if (count($backtrace) > 2)
return $backtrace[count($backtrace)-2];
elseif (count($backtrace) > 1)
return $backtrace[count($backtrace)-1];
else
return false;
}
Full example:
<?php
function debug_caller_data()
{
$backtrace = debug_backtrace();
if (count($backtrace) > 2)
return $backtrace[count($backtrace)-2];
elseif (count($backtrace) > 1)
return $backtrace[count($backtrace)-1];
else
return false;
}
function write($var)
{
var_dump(debug_caller_data());
}
function caller_function()
{
$abc = '123';
write($abc);
}
$abc = '123';
write($abc);
caller_function();

Categories