Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass an object as parameter in PHP [closed]

Tags:

php

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 ?

like image 669
Hoan Dang Avatar asked Feb 17 '12 17:02

Hoan Dang


People also ask

Does PHP pass objects by reference?

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.

Can we pass object in params?

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.

Is PHP pass by value or pass by reference?

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.

What is passing object as argument?

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.


1 Answers

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.

like image 194
Tim Cooper Avatar answered Sep 28 '22 03:09

Tim Cooper