SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    Hi there! Owen's Avatar
    Join Date
    Jan 2000
    Location
    CA
    Posts
    1,165
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Now, I'll admit I'm used to Perl, but this gets me. Why oh why does this not work? It's so simple, I'm embarassed even asking about it. It just makes no sense.

    PHP Code:
    <?
    $q 
    ":";

    function 
    test($x) {
            
    $q .= $x;
    }

    test("hello");
    test("hi");

    echo(
    $q);

    ?>
    I know it's something obvious, so what is it?

    Owen

  2. #2
    ********* Callithumpian silver trophy freakysid's Avatar
    Join Date
    Jun 2000
    Location
    Sydney, Australia
    Posts
    3,798
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hehe, I'm guessing your expected results were:
    :hellohi
    but your actual results are
    :

    Is this right? This is because the global variable $q is not in scope inside function test($x) and so the variable $q inside that function is a completely different variable with local scope. Two solutions:

    a) Quick and dirty solution:
    PHP Code:
    function test($x) {
       global 
    $q;
       
    $q .= $x;

    More pure from a design perspective:
    PHP Code:
    function test($x, &$q) {
       
    $q .= $x;


  3. #3
    Hi there! Owen's Avatar
    Join Date
    Jan 2000
    Location
    CA
    Posts
    1,165
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Haha! Thanks for the quick response. Just what I was looking for (as I said, I'm too used to perl (and I guess java too))

    Thanks,
    Owen


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •