-1

我需要将在父类中找到的变量传递给扩展类,但我得到的只是变量未定义的通知。

我不确定出了什么问题,我的直觉说这很容易解决,但由于某种原因我看不到它。

<?php
class trackem {

public $hostnm;
public $ip;
public $info;

public function __construct() {
}

public function getNm($hostnm){
    $hostnm = gethostbyaddr($_SERVER['REMOTE_ADDR']);
    //echo $hostnm;
}
public function getIp($ip){
    $ip =  $_SERVER['SERVER_ADDR'];
    //echo $ip;
}
public function getBrws($info){
    $info = get_browser(null, true);
    //print_r($info);
}

}

class trackem2file extends trackem{

function wrtInfo(){
    //parent::getBrws($info);
    //parent::getIp($ip);
    //parent::getNm($hostnm);
    parent::__construct();

    $this->hostnm = parent::getNm($hostnm);
    $this->ip = parent::getIp($ip);
    $this->info = parent::getBrws($info);
    $this->filename = 'txt/trackfile.txt';

    $this->fh = fopen($this->filename, 'w');
    fwrite($this->fh, $this->hostnm . '\r\n');
    fwrite($this->fh, $this->ip . '\r\n');
    fwrite($this->fh, $this->info . '\r\n');
    fwrite($this->fh, '--------------------' . '\r\n');
    fclose($this->fh);

}
}

$track2 = new trackem2file();
$track2->wrtInfo();
?>

我已经尝试找到解决方案大约 2 天了,并且我已经阅读了一些关于对象继承和变量未加载到扩展类的其他帖子,但对帮助我解决这个问题没有足够的帮助。所以我现在请求你的帮助。

提前致谢。

4

2 回答 2

3

你需要像这样使用它们,你错过了$this->

$this->info;
$this->ip;
$this->hostnm;

尝试这个:

<?php
class trackem
{
    public $hostnm;
    public $ip;
    public $info;

    public function __construct()
    {
    }

    public function getNm()
    {
        $this->hostnm = gethostbyaddr($_SERVER['REMOTE_ADDR']);
    }
    public function getIp()
    {
        $this->ip = $_SERVER['SERVER_ADDR'];
    }
    public function getBrws()
    {
        $this->info = get_browser(null, true);
    }

}

class trackem2file extends trackem
{
    function wrtInfo()
    {
        parent::__construct();

        $this->getNm();
        $this->getIp();
        $this->getBrws();
        $filename = 'txt/trackfile.txt';

        $fh = fopen($filename, 'w');
        fwrite($fh, $this->hostnm . '\r\n');
        fwrite($fh, $this->ip . '\r\n');
        fwrite($fh, $this->info . '\r\n');
        fwrite($fh, '--------------------' . '\r\n');
        fclose($fh);

    }
}

$track2 = new trackem2file();
$track2->wrtInfo();
?>
于 2012-11-16T14:55:00.267 回答
0
class trackem
{
    public $hostnm
    public $ip;
    public $info;

    public function __construct()
    {
        $this->hostnm = gethostbyaddr($_SERVER['REMOTE_ADDR']);
        $this->ip = $_SERVER['SERVER_ADDR'];
        $this->info = get_browser(null, true);
    }
}

class trackem2file extends trackem
{
    public function wrtInfo()
    {
        $data = join(PHP_EOL, [$this->hostnm, $this->ip, $this->info]);
        file_put_contents('txt/trackfile.txt', $data);
    }
}

$track2 = new trackem2file();
$track2->wrtInfo();
于 2012-11-16T15:14:24.980 回答