I thought I could call a function twice in PHP

by 9 replies
11
Newbie here,

I thought I had a solution to my looping problem

function foo($a,$b) {

do stuff

}

$a='blah'
$b='yuck'

foo($a,$b)

// but I cannot run it a second time with the same variables

$a='yum'

$b='mmm'

foo($a,$b)

//The function will not run the second time around. Is this a php rule I haven't run across yet?

Thanks

Rick
#programming #call #function #php #thought
  • There's nothing that necessarily says you can't use a function twice in PHP. I'm wondering what kinds of stuff is in your function and I'm also wondering if there's something in your program that's preventing the function from being called a second time.
  • it should run perfectly without an issue, can you post your code not pseudo code maybe it has an error in it?
    • [1] reply
    • Too long and sloppy

      Works in the first call works in the second call, but not both function calls. Also works with include. Might just be too big.

      Rick
      • [1] reply
  • Hi there,

    if the second variable initialization value is constant, I would suggest you make a "recursive function"!

    Just declare and initialize it in your too method one the main part of the function is executed successfull and then call it again, like:

    //global counter variable...

    $counter = 0;

    function doSmth($a,$b) {



    //code to be executed here...

    $a = '1';
    $b = '2';

    if($counter < 1) {


    doSmth($a, $b);

    $counter++;

    }
    }

    Hope I could help you out a little bit.

    Regards,
    Peter
    • [ 1 ] Thanks
    • [1] reply
    • With all due respect, Sir, I disagree with this suggestion, especially for someone who is just learning the ropes. Recursive functions have great utility for very specific problems which are recursive in nature, but the vast majority of problems are not. (e.g., I recently used this approach to display an affiliate genealogy tree, where referrers have referrers have referrers....)

      Yes, yes, I know that recursion is taught in school, but rarely is the solution presented in conjunction with the types of situations where it should actually be used.

      My main concern is that someone who is just starting out, who's having difficulty in calling a function twice, or starting to learn about boolean logic and parentheses, can accidentally create far more problems than recursion might ever solve.

Next Topics on Trending Feed