D
D
Dimas1232014-01-16 14:51:26
PHP
Dimas123, 2014-01-16 14:51:26

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

5 answer(s)
N
Nikolai Vasilchuk, 2014-01-16
@Anonym

<? 
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);

Z
zhogar, 2014-01-16
@zhogar

Try adding another class, something like:

class Result
{
private $result; 
    function __construct(...) 
    { 
    $this->result = ...; 
    } 	
    public function Calc() 
    { 
        ...
    } 
}

Z
zhogar, 2014-01-16
@zhogar

For objects to interact with each other, it is better to use pointers to these objects.

M
Mikhail Shatilov, 2014-01-16
@iproger

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

S
Sild, 2014-02-04
@Sild

offtop: Please stop mixing English and transliteration. If you don't know how to spell a word, ask the translators.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question