PHP: newbie question - variables inside a class?
i'm having this code:
class c_web
{
var $root_fso;
function __construct($webname)
{
$th开发者_StackOverflow中文版is->webname = $webname;
$root_fso = $_SERVER{'DOCUMENT_ROOT'};
}
function init($template_filename)
{
echo $root_fso;
}
}
my question: what's wrong with the syntax with the $root_fso variable as it returns blank?
thanks
You need to explicitly say $this->root_fso
because PHP doesn't need you to declare a local variable so $root_fso
is always going to refer to a local. Use $this->
when accessing fields of the class.
OTHER OBSERVATIONS:
Also $_SERVER{'DOCUMENT_ROOT'}
should be $_SERVER['DOCUMENT_ROOT']
? Also $this->webname
refers to a field that is not defined, you should define it.
It's $this->root_fso
. In PHP, the $this->
is necessary to access any class member.
It is a class variable so you have to reference with $this
class c_web
{
var $root_fso;
function __construct($webname)
{
$this->webname = $webname;
$this->root_fso = $_SERVER['DOCUMENT_ROOT'];
}
function init($template_filename)
{
echo $this->root_fso;
}
}
<?php
class c_web
{
var $root_fso;
function __construct($webname)
{
$this->webname = $webname;
$this->root_fso = $_SERVER{'DOCUMENT_ROOT'};
}
function init($template_filename)
{
echo $this->root_fso;
}
}
$a = new c_web("a");
$a->init("a");
?>
There's two things wrong here.
To start with, $_SERVER{'DOCUMENT_ROOT'};
should be $_SERVER['DOCUMENT_ROOT'];
Second, the value of $root_fso
changes only in __construct. You would need to change the second line of your __construct function to: $this->root_fso = $_SERVER['DOCUMENT_ROOT'];
精彩评论