开发者

PHP: newbie question - variables inside a class?

开发者 https://www.devze.com 2023-02-18 15:24 出处:网络
i\'m having this code: class c_web { var $root_fso; function __construct($webname) { $th开发者_StackOverflow中文版is->webname = $webname;

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'];

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号