Thursday, April 28, 2011

How to create my own function with { } in PHP

I want to create my own function loop():

loop($x,$y){
    //do something
}

it should work like for, foreach operators:

$y=count($array); 
for($x=0; $x<$y; $x++){ 
     //do something 
}

How to create functions like this with { } in PHP? (NOT a regular function)

From stackoverflow
  • You can't.

    Constructs like for or foreach are part of php syntax.

    If you want to create regular function just use function keyword:

    function some_func($x, $y)
    {
    ....
    }
    
  • There will be lambda functions - that's what you want to do - in PHP 6. Right now you have to stick with "normal" functions.

    vartec : "in PHP 6". in PHP 5.3 actually.
    OIS : If this is the right answer, we need a different question. For the question as is (how to create a function), the answer by empi is correct.
    John Gietzen : @OIS he said "create a function with { } NOT a regular function" meaning EXACTLY that he wants lambda functions. +1.
    OIS : You are correct. The question could be a bit better though. :)
    hasen j : if lambda function in php are to be like in python (i.e. anonymous functions) then this DOES NOT answer the question. He wants to create a new construct (like the for loop), not a function.
  • At a more advanced level, you could create a class and iterate that, in which you can pretty much change the execution flow during execution (while iterating).

    Here's the docs: http://php.net/iterator

  • Another thing which you can if you are really serious about your function/s you can write it a php extension which will you some flexibility...http://devzone.zend.com/node/view/id/1021 I must warn you though..it's not as easy....

0 comments:

Post a Comment