Pass object as parameter in PHP

In Java, I can pass an object directly in the parameter

public int foo (Bar bar) { ... call the methods from Bar class } 

So how can I do the same with PHP. Thanks This is my code:

 class Photo { private $id, $name, $description; public function Photo($id, $name, $description) { $this->id = $id; $this->name = $name; $this->description = $description; } } class Photos { private $id = 0; private $photos = array(); private function add(Photo $photo) { array_push($this->photos, $photo); } public function addPhoto($name, $description) { add(new Photo(++$this->id, $name, $description)); } } $photos = new Photos(); $photos->addPhoto('a', 'fsdfasd'); var_dump($photos); // blank 

If I change the add function

 function add($name, $description) { array_push($this->photos, new Photo(++$this->id, $name, $description)); } 

This works great. So what's wrong?

+4
source share
1 answer

You do this in exactly the same way as with some syntax changes, of course:

 public function foo(Bar $bar) { // $bar->method() } 

Remember that you can use hint type for classes and arrays.

+10
source

Source: https://habr.com/ru/post/1397087/


All Articles