Answer the question
In order to leave comments, you need to log in
What is the difference between returned array and objects?
Guys, help me understand what the difference is in the returned result.
Why return objects in this case? How will this help me with a specific example?
I want to figure it out finally)
1. Get an array
class Product
{
public $data = [];
public function getAll(){
foreach(range(0, 10) as $v){
$this->data[$v]['id'] = $v;
$this->data[$v]['name'] = 'Name';
$this->data[$v]['price'] = rand(100, 500);
}
return $this->data;
}
}
$a = new Product();
var_dump($a->getAll());
class Product
{
public $id;
public $name;
public $price;
public function __construct(int $id, string $name, int $price){
$this->id = $id;
$this->name = $name;
$this->price = $price;
}
}
class ProductCollection
{
public $data = [];
public function getAll(){
foreach(range(0, 10) as $v){
$this->data[] = new Product($v, 'Name', rand(100, 500));
}
return $this->data;
}
}
$b = new ProductCollection();
var_dump($b->getAll());
Answer the question
In order to leave comments, you need to log in
Why return objects in this case?Your question suggests that you do n't understand the difference between an object and an array .
How will this help me with a specific example?OK. Example. Let's say that your Product object doesn't just contain properties, but each property.....yes, it's also an object. So, let's rewrite the constructor, add a few new properties, for example:
public function __construct(int $id, string $name, int $price, $decription, $discount_date){
$this->id = $id;
$this->name = new EntityText($name);
$this->price = new Price($price);
$this->decription = new EntityText($decription);
$this->discount_date = new MyDate($discount_date); // MyDate extends \Datetime
}
<html>
<div id="product<?=$obj->getId()?>">
<h1><?=$obj->getName()->getTextValue()?></h1>
<p>Цена: <?=$obj->getPrice()->getUSD()->asText()?></p> <!-- например, выведет "101 доллар США" (c правильной формой слова "доллар/доллара/долларов") -->
<p><?=$obj->getDescription()->getTextValue(200)?></p>
<p>Скидка действут <?=$obj->getDiscountDate()->formatAsHuman()?></p> <!-- выведет "еще 2 дня" -->
</div>
</html>
A little experience and big projects - and an understanding of what is
worse, what
will become simple and natural.
Moreover, even in simple projects, you can search for a long time for the reason why it does not work.
I suggest that the doubters determine what the problem of the last example is.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question