0

我正在尝试在 PHP 中获取类的属性

class Test(){
    public function import($data) {
        $im = new import($this, $data);
        $im->getInfo();

        $this->fileInfo = $im->getRecord();
        new ImportData($this, $this->fileInfo);
        return true;
    }

    public function getFilePath(){
        return $this->fileInfo;
    }
}

在我的另一个文件中。

$import = new Test();

$filePath = $import ->getFilePath();

//$filePath returns nothing becasue $this->fileInfo is not init yet.  


//my other codes here.
//my other codes here.

//call import method here.
$import ->import($data);

我需要调用getFilePathbeforeimport方法,但我只能获取$this->fileInfoinimport方法。反正这周围有吗?非常感谢!

4

1 回答 1

1

许多示例之一...在类中使用您的构造方法来初始化您在类范围内需要的变量和方法。

class TestClass
{
   private $variable // should initialized in construct to be available via $this->variable class wide
   public function __construct($data)
    {
       // initialize methods and code here so they will be available throughout the calss
       $this->variable = $this->getinfo($data); // this will be initialized when you instantiate your class object.
    }

   //etc methods
}
于 2013-04-25T21:00:56.280 回答