Kepesk Posted February 1, 2011 Share Posted February 1, 2011 Hello! I'm having trouble with a class that extends another, and I don't think I understand the 'extends' concept properly. I've had my nose in various manuals, but I haven't had any luck figuring it out. Here's a simplified version of my code: class Position { private $latitude = 0; private $longitude = 0; public function getLatitude(){ return $this->latitude; } public function getLongitude(){ return $this->longitude; } } class Coordinates extends Position { function __construct($nlat, $nlong){ $this->latitude = $nlat; $this->longitude = $nlong; } } $lat = -123; $long = 44; $coordFirst = new Coordinates($lat,$long); print($coordFirst->getLatitude()); I expect -123 to be printed, but I always get 0 instead. Could someone let me in on what I'm missing here? Thanks a bunch! Quote Link to comment Share on other sites More sharing options...
requinix Posted February 1, 2011 Share Posted February 1, 2011 You declared the $latitude and $longitude as private. That means only the Position class can access them. And that's fine: you have getLatitude() and getLongitude() to access them. But it's not fine because Coordinates tries to set them. You should have seen a couple error messages about how that isn't allowed - probably have PHP set to not show any errors. The "best" course is to give a constructor to Position as well, then have Coordinates' call it. class Position { public function __construct($lat, $long) { $this->latitude = $lat; $this->longitude = $long; } } class Coordinates extends Position { public function __construct($nlat, $nlong) { parent::__construct($nlat, $nlong); } } The other option, which I tend to prefer, is declaring non-public variables as protected. It'll mean Coordinates can access the variables just fine, but it means that the class will have to be responsible for what happens after - it might accidentally break how the Position class works. (And that's the tl;dr reasoning for things like getters and setters.) Quote Link to comment Share on other sites More sharing options...
Kepesk Posted February 1, 2011 Author Share Posted February 1, 2011 The "best" course is to give a constructor to Position as well, then have Coordinates' call it. Wow thanks, that solved it perfectly! Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.