SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Addict seanmayhew's Avatar
    Join Date
    Aug 2002
    Posts
    209
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    $this-> explained

    Could someone please give me a definition for using:

    $this->somevarible

    within a class file or function in laymans terms. Theres a concept here that I'm not grasping. Why is this useful or necessary?

  2. #2
    SitePoint Wizard Mincer's Avatar
    Join Date
    Mar 2001
    Location
    London | UK
    Posts
    1,140
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    PHP Code:
    class Test
    {
        var 
    $foo ;

        function 
    Test$bar )
        {
            
    $foo $bar ;
        }

        function 
    getFoo()
        {
            return 
    $foo ;
        }
    }

    $test =& new Test'HelloWorld' ) ;

    echo 
    $test->getFoo() ; 
    This example will print nothing as the variable $foo in each of the class functions is a diffrent variable a far as php is concerned (it's in local scope for the functions).

    However, if you consider this example:

    PHP Code:
    class Test
    {
        var 
    $foo ;

        function 
    Test$bar )
        {
            
    $this->foo $bar ;
        }

        function 
    getFoo()
        {
            return 
    $this->foo ;
        }
    }

    $test =& new Test'HelloWorld' ) ;

    echo 
    $test->getFoo() ; 
    Then each function of the class knows that $this->foo is the member variable of itself.

    Note that in the constructor, $bar is in local scope for the function, so it does not need any other identification.

    So, $this is an alias for the current instance of the class. So $this->foo refers to the variable $foo that is associated with the class $test. Of course, you have no idea that you will call the variable $test when you write the class, so you use the $this-> notation.

    It's one of those things that will just twig one day and you'll get it.

    Matt.
    Last edited by Mincer; Dec 9, 2002 at 10:13.

  3. #3
    SitePoint Wizard siteguru's Avatar
    Join Date
    Oct 2002
    Location
    Scotland
    Posts
    3,631
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    It may also help if you think of the -> as dot (if you have any ASP or JavaScript experience).
    Ian Anderson
    www.siteguru.co.uk


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
  •