View Single Post
Old 04-19-2009, 05:52 AM  
calmlikeabomb
Confirmed User
 
calmlikeabomb's Avatar
 
Join Date: May 2004
Location: SW Palm Bay, Florida
Posts: 1,323
Quote:
Originally Posted by KRosh View Post
Why does this work? Why does this show the email address?
#1

Code:
<?php
class person {
    private $email = “foo”;
    function showEmail() {
        echo $this->email;
    }
}
class user extends person {}
$u = new user();
$u->showEmail();
This works because the email property is within scope of the method accessing it.

Quote:
Originally Posted by KRosh View Post
but this doesn’t?
#2

Code:
<?php
class person {
    private $email = “foo”;
}
class user extends person {
    function showEmail() {
        echo $this->email;
    }
}
$u = new user();
$u->showEmail();
This doesn't work, because email is out of scope. If you set it to "protected" then extending classes will be able it inherit the email property.

Quote:
Originally Posted by KRosh View Post
Also, why does this work
#3

Code:
<?php
class person {
    private $email = “foo”;
    function showEmail() {
        echo $this->email;
    }}
class user extends person {
    function showEmail() {
        parent::showEmail();
    }
}
$u = new user();
$u->showEmail();
This works because, again the property is within scope of the method calling it.

Also, you shouldn't be defining properties like that. That should be done in the constructor. The only time you'd do that are with class constants.

http://www.php.net/construct
__________________
subarus.

Last edited by calmlikeabomb; 04-19-2009 at 05:55 AM..
calmlikeabomb is offline   Share thread on Digg Share thread on Twitter Share thread on Reddit Share thread on Facebook Reply With Quote