Answer the question
In order to leave comments, you need to log in
Object interaction in PHP
To study OOP PHP came up with the following problem:
There is a class "City". With the "Length" property.
There is a class "Auto". With the "Speed" property.
A "City" object is created, which should display a message about the time spent for the "Auto" object to pass the entire length of the "City". Provided that this object "Auto" exists.
I don't know how to make them interact:
<?
class Gorod
{
private $dlina;
function __construct($dlina)
{
$this->dlina = $dlina;
}
public function getDlina()
{
return $this->dlina;
}
}
class Avto
{
private $speed;
function __construct($speed)
{
$this->speed = $speed;
}
public function getSpeed()
{
return $this->speed;
}
}
$a = new Avto("20");
$g = new Gorod("100");
//Нужно как-то изменить класс Gorod, что бы он выдал "5" исходя из-того, что существует объект Avto со скоростью 20 и объект город имеет длину 100.
?>
Answer the question
In order to leave comments, you need to log in
<?
class City {
private $length;
function __construct($length) {
$this->length = $length;
}
public function getLength() {
return $this->length;
}
}
class Auto {
private $speed;
function __construct($speed) {
$this->speed = $speed;
}
public function getSpeed() {
return $this->speed;
}
public function howLongToGo($length) {
return $length / $this->speed;
}
public function howLongToGoThrowCity(City $city) {
return $city->getLength() / $this->speed;
}
}
$a = new Auto(20);
$c = new City(100);
print $a->howLongToGo($c->getLength());
// Или так
print $a->howLongToGoThrowCity($c);
Try adding another class, something like:
class Result
{
private $result;
function __construct(...)
{
$this->result = ...;
}
public function Calc()
{
...
}
}
For objects to interact with each other, it is better to use pointers to these objects.
You have an error: "City", which should display a message about the time spent passing the "Auto" object.
There is a City, Auto inherits from City. Auto has a Calc method that uses $this->length (use length..) and $this->speed.
PS The city does not know about the car, and the car depends on the city, IMHO :)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question