Page 1 of 1

Function redeclaration error, from another instance.

Posted: Wed Jan 12, 2005 6:46 pm
by karlmdv
The following code gives the error "Fatal error: Cannot redeclare bar() (previously declared in /var/www/htdocs/tmp/tmp.php:6) in /var/www/htdocs/tmp/tmp.php on line 5"

I believed that the function bar() would be out of scope. Am I misunderstading something about scope?

Generally though what I need to do is have a function, nested inside a member function of a class, and be able to instantiate that class more than once in a script. Is this possible?

TIA,
Karl.

Code: Select all

<?php
class foob&#123;

    function foo()&#123;
        function bar()&#123;
            echo "bar";
        &#125;
        echo "foo";
        bar();
    &#125;

    function foo2()&#123;
        echo "foo2";
    &#125;
&#125;

$foo = new foob();
$foo->foo(); // echos "foobar"
$foo->foo2(); // echos "foo2"

$foo2 = new foob();
$foo2->foo2(); // echos "foo2"
$foo2->foo(); // Fatal error
?>

Posted: Wed Jan 12, 2005 6:53 pm
by feyd
you cannot have a function declaration inside another function.

Posted: Wed Jan 12, 2005 8:26 pm
by karlmdv
Functions inside functions are allowable. From the php manual, language.functions.html

Code: Select all

Example 17-3. Functions within functions
<?php
function foo() 
&#123;
  function bar() 
  &#123;
    echo "I don't exist until foo() is called.\n";
  &#125;
&#125;

/* We can't call bar() yet
   since it doesn't exist. */

foo();

/* Now we can call bar(),
   foo()'s processesing has
   made it accessible. */

bar();

?>

Posted: Wed Jan 12, 2005 8:42 pm
by feyd
because class foob() was already instantiated once, and foo() run, bar() already existed in the global namespace.