You are confusing 3 different things here:
- Global variables, which exist outside any function, class, or object, have to be "imported" into the current scope with the
global
keyword. They are generally considered bad practice as they lead to code which "magically" transports data from one place to another, making reuse, testing, and debugging more difficult.
- Object properties are declared in a
class
definition, and belong to an instance of that class (or to the class itself, in the case of static
variables). They are accessed with the syntax $object->property
. The private
keyword means the variable can only be seen inside the class, by using the special variable $this
, meaning "this object I am inside", e.g. echo $this->prop1;
- Function arguments are passed in when you call a function. Inside the function, they are local variables with the names given in the function definition, so do not need to be imported or prefixed in any way. Object methods are basically just functions "attached to" a particular object, and work in the same way.
In your example, you have a comment against an object property here...
private $prop2; // this contains an array object
...but you then say that using that variable (with $this->prop2
) gave an error (which you haven't actually shown us properly yet) suggesting that it was not an array. (As mentioned in the comments, "array object" is an odd choice of words. I'm going to assume you just meant "array" for now.)
You then "solve" this by instead using a global variable...
global $prop2;
$obj = new SomeClass($prop2);
...which is a completely different variable.
You also show a definition of a method for setting your private property...
public function set_prop2($prop2)
...but you never show us where you're calling it.
You've annotated it with a comment suggesting where you think it's being called...
// value coming from other class that returns array object
...but the entire question hinges on where that function argument comes from.
One of the things that makes your code hard to read is that the object property, the global variable, and the function argument all have the same name. This doesn't make them the same variable.
What you could try is separating out the different variables, and looking at each in turn:
class MyClass {
private $private_property;
public function set_prop2($new_value_for_prop2) {
var_dump($new_value_for_prop2); // what's the value passed in?
$this->private_property = $new_value_for_prop2;
}
public function func1() {
var_dump($this->private_property); // what value is it now?
}
}
$function_return = some_function();
var_dump($function_return); // is it an array?
$obj = new MyClass;
$obj->set_prop2($function_return); // should show you the value being set
$obj->func1(); // should show the same value again