www.webdeveloper.com
Results 1 to 3 of 3

Thread: Class with $_GET as variable doesn't work?

  1. #1
    Join Date
    Oct 2011
    Posts
    54

    Class with $_GET as variable doesn't work?

    Hello,
    I can't figure out why this doesn't work. Because aren't both ways exactly the same?

    PHP Code:
    <?php

        
    class checkBlog
        
    {
            var 
    $id;
        
            function 
    __construct()
            {
                
    $this->id=$_GET['b'];
            }

        
        }

    $checkBlog = new checkBlog();
    ?>
    PHP Code:
    <?php

        
    class checkBlog
        
    {
            var 
    $id $_GET['b'];
        
            function 
    __construct()
            {

            }

        
        }

    $checkBlog = new checkBlog();
    ?>
    but with the second method:
    Code:
    Parse error: syntax error, unexpected T_VARIABLE in

    Thanks in common,
    David

  2. #2
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,321
    Class variables can only be initialized with literal values, not variables nor other expressions. It's a syntax error, but essentially it makes a certain sense, since when it's part of the class variable definition, you'd be trying to make the assignment at compile time (which is before $_GET actually gets populated), whereas when you assign it via the constructor it is assigned at run time, at which point $_GET has been populated. (An alternative would be to pass it as an argument to the constructor, so that it would be less closely coupled with the source of that value and theoretically more re-usable.)
    "Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
    ~ Terry Pratchett in Nation

    eBookworm.us

  3. #3
    Join Date
    Oct 2011
    Posts
    54

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

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



Recent Articles