I am trying to assign a variable to a class in PHP, however I am not getting any results?
Can anyone offer any assistance? The code is provided below. I am trying to echo the URL as shown below, by first assigning it to a class variable.
class PageClass {
var $absolute_path = NULL;
function get_absolute_path(){
$url = $this->absolute_path;
echo $url;
}
}
$page = new PageClass();
$page->absolute_path = "http://localhost:8888/smile2/organic/";
$page->get_absolute_path(); //this should echo the URL as defined above - but does not
It also works for me.
Take a look at a live example of your code here.
However, there are a few things you should change about your class.
First, Garvey does make a good point that you should not be using
var. That’s the older PHP4, less OOP conscious version. Rather declare each variablepublicorprivate. In fact, you should declare each functionpublicorprivatetoo.Generally, most classes have private variables, since you usually only want to change the variables in specific ways. To achieve this control you usually set several public methods to allow client functions to interact with your class only in restricted predetermined ways.
If you have a
getter, you’d probably want asetter, since these are usually used withprivatevariables, like I described above.A final note is that functions named
getusuallyreturna value. If you want todisplaya value, it is customary to use a name likedisplay_pathorshow_path:Live Example Here
There’s a section on classes and objects in the online PHP reference.