In Java, I can pass an object straight in parameter
public int foo (Bar bar)
{
... call the methods from Bar class
}
So how can I do same thing 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 function add
function add($name, $description)
{
array_push($this->photos, new Photo(++$this->id, $name, $description));
}
It works pefectly. So What is wrong ?
In PHP, objects are passed by references by default. Here, reference is an alias, which allows two different variables to write to the same value. An object variable doesn't contain the object itself as value. It only contains an object identifier which allows using which the actual object is found.
We can pass Object of any class as parameter to a method in java. We can access the instance variables of the object passed inside the called method. It is good practice to initialize instance variables of an object before passing object as parameter to method otherwise it will take default initial values.
Introduction. In PHP, arguments to a function can be passed by value or passed by reference. By default, values of actual arguments are passed by value to formal arguments which become local variables inside the function. Hence, modification to these variables doesn't change value of actual argument variable.
To pass an object as an argument we write the object name as the argument while calling the function the same way we do it for other variables. Syntax: function_name(object_name); Example: In this Example there is a class which has an integer variable 'a' and a function 'add' which takes an object as argument.
You do it the exact same way, just with some syntax changes, of course:
public function foo(Bar $bar)
{
// $bar->method()
}
Keep in mind that you can only type hint for classes and arrays.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With