tags:

views:

32

answers:

3

Hello,

I'm wondering; lets say you start an object in a new class; at the beginning of your app.

If you later pass that object into another class; as a variable and add/modfiy something on it. Will it be updated in the original object and its home class?

Or does it become a 'new' object, a different object in a new class? And will it continue to be the same throughout their uses. In either part of the app?

This is for my own clarification, as opposed to a specific coding question.

+4  A: 

objects are passed by reference in php5, so the object is "updated", unless you clone it.

kgb
Great, thank you. Cleared that up.
WiseDonkey
+1  A: 
  • An object doesn't start, it is instantiated, it becomes an instance of a class.
  • You can't pass an object to a class. You can pass it to a function or a method, with no difference in these 2.
  • In every language with proper OOP, objects are passed as reference, so any updates anywhere on that object is reflected everywhere. It's an object, you pass it, modify it, and it remains modified.
Alexander
A: 

You should reread what classes are. Obligatory car example ahead:

Imagine a class Car. Now you create a new instance of that abstract concept:

$myCar = new Car();
$myCar->color = "blue";
$yourCar = new Car();
$yourCar->color = "red";

Every object has its own properties. The class may set default values in its constructor functions, but changing one car's color to orange doesn't impact any other car.

In php5 (php4 oo is weird, I wouldn't suggest it to a beginner), every time you assign from a variable that contains an object, the object reference is copied. Therefore, after executing

$ourCar = $yourCar;
$ourCar->color = "yellow";

, $yourCar->color is "yellow".

phihag