What Are PHP Nested Functions For

What are PHP nested functions for?

There is none basically. I've always treated this as a side effect of the parser.

Eran Galperin is mistaken in thinking that these functions are somehow private. They are simply undeclared until outer() is run. They are also not privately scoped; they do pollute the global scope, albeit delayed. And as a callback, the outer callback could still only be called once. I still don't see how it's helpful to apply it on an array, which very likely calls the alias more than once.

The only 'real world' example I could dig up is this, which can only run once, and could be rewritten cleaner, IMO.

The only use I can think of, is for modules to call a [name]_include method, which sets several nested methods in the global space, combined with

if (!function_exists ('somefunc')) {
function somefunc() { }
}

checks.

PHP's OOP would obviously be a better choice :)

Nested function with PHP

Untested, but you could use an anonymous function:

<?php
function sort_by_key($array, $key) {

$custom_compare = function ($a, $b) use ($key) {
if ($a[$key][0] > $b[$key][0]) { return 1; }
else { return -1; }
};

return usort($array, $custom_compare);
}

Based on a small modification of your existing function.

Further your function still needs a small change:

<?php
function sort_by_key(&$array, $key) {
$custom_compare = function ($a, $b) use ($key) {
if ($a[$key][0] > $b[$key][0]) {
return 1;
} else {
return -1;
}
};

usort($array, $custom_compare);
}

$array = array(
array(
'foo' => array(
2
)
),
array(
'foo' => array(
3
)
),
array(
'foo' => array(
1
)
)
);

sort_by_key($array, 'foo');
var_export($array);

Output:

array (
0 =>
array (
'foo' =>
array (
0 => 1,
),
),
1 =>
array (
'foo' =>
array (
0 => 2,
),
),
2 =>
array (
'foo' =>
array (
0 => 3,
),
),
)

The equivalent of nested functions in php

You can use an anonymous function with the use statement.
http://php.net/manual/en/functions.anonymous.php#functions.anonymous

Try this.

public function setTitle($title) { 
add_filter( 'document_title_parts', function ($t) use ($title) {
$t['title'] = $title; return $t;
});
return $this;
}

Nesting PHP-functions: to what purpose?

Note that the order is important here; you cannot call bar() before calling foo() in your example. The logic here appears to be that the execution of foo() defines bar() and puts it in global scope, but it's not defined prior to the execution of foo(), because of the scoping.

The use here would be a primitive form of function overloading; you can have your bar() function perform different operations depending upon which version of foo() declares it, assuming of course that each different version of foo() indeed defines a bar() function.

Defining short, private PHP nested functions (sub-functions) - best performance? best practice?

Check this answer: anonymous function performance in PHP

As it states it usually does not make much of a difference. If you want to be sure: a lot depends on your specific PHP and server version so you will have to benchmark it.

Having said that, version 2 is more readable than version 1, but version 3 - a class with private function would be the most readable solution as your code tells other programmers clearly that calc() is not used elsewhere.


class something {
static public function doSomething($a, $b, $c) {
if($a>$c) return self::calc($c);
else if($a<$b) return self::calc($b);
else return self::calc($c);
}
static private function calc($val) { /* do some calculation */ }
}

PHP nested functions use a variable of the outer one in the inner one

Try to use this

function sortBy(&$arr, $key) {
$cmp = function($a, $b) use ($key) {
return $a[$key] < $b[$key] ? -1 :
$a[$key] == $b[$key] ? 0 : 1;
};
return uasort($arr, $cmp);
}

php call nested function

Its called Method Chaining.

Method chaining works because a function or a method of the class always returns object which further call another function.

Basically it returns it self.

Ex:

public function method1() {
// method content ...
return $this;
}

public function method2() {
// method content ...
return $this;
}

Please refer the following link to read more on Method Chaining,

http://www.techflirt.com/tutorials/oop-in-php/php-method-chaining.html

There will be more articles you could find on this.

Access variable from function inside of nested function

You have two options:

Give $content as a parameter

function foo() {
$content = 'foobar';

function bar($content) {
echo $content; // echos something
}
}

Take $content outside of the function and use global there.

$content = '';

function foo() {
global $content;

$content .= 'foobar';

function bar($content) {
global $content;

echo $content; // echos something
}
}

Difference between how php and javascript execute a nested function

Its a scope thing. You could have as easily - in javascript - written "var b = function()". "b" is just a variable of type function defined within the scope of the function a. In PHP, both "a" and "b" are global functions, but it's the job of function "a" to define "b", so it won't get defined until "a" is called. Consider this example...

function a($x) {
if ($x) {
function b() { echo "x not empty"; }
} else {
function b() { echo "x empty"; }
}
}
a(1); // Defines function b
b(); // x not empty
a(0); // PHP Fatal error: Cannot redeclare b() (previously declared...

You can see by the failure to redefine "b", that "b" is a real, globally scoped function. Function "a" could use various criteria to define the function for a particular purpose in different runs. Clearly, in this case, it wouldn't make sense to call function "b" before function "a" has decided how to define it.

I don't, by the way, think the example above is very good coding practice, but it does serve to illustrate the point.

The PHP code most similar to your javascript code would be:

function a() {
$b = function() {
echo "'b' says inner";
};
$b(); // Demonstrating the function can be used inside "a"
}
a(); // 'b' says inner

$b is a variable of type function, which can only be used within function "a".



Related Topics



Leave a reply



Submit