tags:

views:

370

answers:

4

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)

+13  A: 

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)
{
....
}
empi
+2  A: 

There will be lambda functions - that's what you want to do - in PHP 6. Right now you have to stick with "normal" functions.

Koraktor
"in PHP 6". in PHP 5.3 actually.
vartec
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.
OIS
@OIS he said "create a function with { } NOT a regular function" meaning EXACTLY that he wants lambda functions. +1.
John Gietzen
You are correct. The question could be a bit better though. :)
OIS
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.
hasen j
+5  A: 

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

Flavius
+2  A: 

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....

Ronald Conco