Chris Fletcher Chris Fletcher - 20 days ago 6
PHP Question

Can't seem to access an object's properties

I have a simple function:

function myFunction($this){
var_dump($this);
}


Which outputs this:

object(MyClass)#810 (20) {
["course_id"]=>int(43)
// ...more properties
}


However, if I try to access "course_id" on the object, nothing gets output:

var_dump($this->course_id);


In the class definition,
course_id
is public:

class MyClass extends AnotherClass {

public $course_id = 0;
}


What am I doing wrong? Thank you :)

Answer

It's because you're using the name $this which is a pseudo-variable that becomes available when a method is called from within an object context, but you're not calling it within an object context, you're calling it from within a function context.

Change the parameter name and it works:

class MyClass {
    public $course_id = 0;
}

function myFunction($temp) {
    var_dump($temp->course_id);
}

$test = new MyClass();
myFunction($test);