在扩展类中使用父变量的问题

时间:2012-11-16 14:51:10

标签: php

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

我不确定出了什么问题,我的直觉说这是一个简单的解决办法,但出于某种原因,我看不到它。

<?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天了,我已经阅读了一些关于对象继承和变量未加载到扩展类的其他帖子,但是没有帮助我解决这个问题。所以我现在请求你的帮助。

提前致谢。

2 个答案:

答案 0 :(得分: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();
?>

答案 1 :(得分: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();