Function redeclaration error, from another instance.

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
karlmdv
Forum Newbie
Posts: 2
Joined: Wed Jan 12, 2005 6:40 pm

Function redeclaration error, from another instance.

Post 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
?>
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

you cannot have a function declaration inside another function.
karlmdv
Forum Newbie
Posts: 2
Joined: Wed Jan 12, 2005 6:40 pm

Post 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();

?>
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

because class foob() was already instantiated once, and foo() run, bar() already existed in the global namespace.
Post Reply