开发者

How to implement scoped function in PHP?

function parent($key)
{
     function son()
     {
         global $key;
     }
}

I want to achieve this:

  1. son can access the $key of开发者_开发百科 parent

As it's quite a simple function,I don't want to change parent into a class

OK,I've been told that function are global anyway.Is there a way for son to get $key of parent then?


All functions in PHP have the global scope - they can be called outside a function even if they were defined inside and vice versa.

Refer the PHP manual for more details


Since PHP 5.3 you can do:

function parent($key) {
    $son = function() use (&$key) {
        var_dump($key);
    };
    $son();
}
parent('foo');

About usort -- are you looking for something like this?

$key = 'foo';
$arr = array(
    array(0, 'foo' => 1),
    array(1, 'foo' => 4),
    array(2, 'foo' => -2),
);

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

var_dump($arr);


You could do this in OOP and you can not create one function inside another. However, one way may be like this:

// make sure that parent function exists
if (function_exists('parent'))
{
   // ok fine, now create the son function
   function son()
   {
       global $key;
   }
}


Why couldn't you consider OOP approach? Define class with methods using different modifiers: public/private... Of course I'm simplify, but going this direction will help to achieve your goal.

If you insist of not using OOP, but still need this happens read this: http://www.steike.com/code/php-closures/ and this http://wiki.php.net/rfc/closures. Since closures it's only way I know how you can do it without OOP, but using functional programming.


Since you mention usort(), can this work?

$arr = array('foo', 'bar', 'tork', 'zug');

usort($arr, 'mysort');

function mysort($a, $b) {
    $a = do_something_with_a($a);
    $b = do_something_with_b($b);

    return strcmp($a, $b);
}

function do_something_with_a($val) {
    return strrev($val);
}
function do_something_with_b($val) {
    return strrev($val);
}

print_r($arr);


from my understanding, you need a function that generates custom sorting function for you, depending on the passed parameter, along the lines of

function sorter($param) {
    return function($a, $b) use($param) {
        if($param == 'asc') return $a - $b;
        if($param = 'desc') return $b - $a;
    };
}

$a = array(1, 6, 2, 5, 3, 4);
usort($a, sorter('asc'));
print_r($a);
usort($a, sorter('desc'));
print_r($a);

(php 5.3 only)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜