Jump to content

Difficulty with Extended Class


Kepesk

Recommended Posts

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!

Link to comment
https://forums.phpfreaks.com/topic/226297-difficulty-with-extended-class/
Share on other sites

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.)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.