php构造函数undefined属性

时间:2018-01-26 15:36:46

标签: php constructor undefined

对于我正在处理的程序,我想从navi.php中创建一个imageMachine类(imagmachine.php)的实例。

在Navi.php中输入以下代码:

$target_dir = "";
$target_file = $target_dir . basename($_FILES["fileToUploadName"]["name"]);
require_once (__ROOT__.'/imagemachine.php');
$imageMachineSubject = new ImageMachine ($target_dir, $target_file);
$imageMachineSubject -> saysth();

,应该创建一个新的imageMAchine对象并调用它的saysth()方法。参数来自ui文件中的表单。

在imageMachine中,我想明显地对图像做一些事情,但那不是问题。目前我一直在碰壁,当我只想让实例从构造函数中简单地保护params($ target_dir,$ target_file)时,我可以使用其他方法中的值。

<?php
class ImageMachine {

  public $imageFile;
  public $imageExtension;

  public function __construct ($target_dir, $target_file)
  {
    $this->imageFile= $target_file;

    echo $imageFile;
    // Undefined variable: imageFile in C:\xampp\htdocs\imagemachine.php on line 12
  }

  function saysth (){
    echo ($this->$imageFile);
    // Undefined property: ImageMachine::$image_file in C:\xampp\htdocs\imagemachine.php on line 17
    // Undefined property: ImageMachine::$  in C:\xampp\htdocs\imagemachine.php on line 17
    echo ($imageFile);
    // Undefined variable: imageFile in C:\xampp\htdocs\imagemachine.php on line 19
    echo $imageFile;
    // Undefined variable: imageFile in C:\xampp\htdocs\imagemachine.php on line 21
  }

}
?>
<html>
</html>

错误消息作为注释添加到代码中。尝试了很多变种,主要来自教程和其他资源,到目前为止没有任何工作,因此有点想法在哪里看当下。我在这里弄错了什么?

编辑: 一些代码的形式正确:

  public function __construct ($target_dir, $target_file)
  {
    $this->imageFile = $target_file;
    $this->imageExtension= pathinfo($target_file,PATHINFO_EXTENSION);
  }

  function saysth (){
    echo ($this->imageFile);
    echo "blah";

    switch ($this->imageExtension) {
      case 'jpg':
      case 'jpeg':

2 个答案:

答案 0 :(得分:1)

如果您的功能saysth()应该使用

echo $this->imageFile;

请注意,在实例变量名称(imageFile)之前不应该有$符号 - 与您在构造函数中已经使用的符号相同。

答案 1 :(得分:1)

我将通过消息解释错误消息:

// Undefined variable: imageFile in C:\xampp\htdocs\imagemachine.php on line 12

$this和本地范围是不同的东西。因此$this->x不等于$x

// Undefined property: ImageMachine::$image_file in C:\xampp\htdocs\imagemachine.php on line 17
// Undefined property: ImageMachine::$  in C:\xampp\htdocs\imagemachine.php on line 17

这是一个$太多了。它应该是$this->imageFile。它正在查找名为$imageFile $this的值的属性,该属性不存在(请参阅上面的原因)。

这也导致下一行中的错误:

// Undefined variable: imageFile in C:\xampp\htdocs\imagemachine.php on line 19
// Undefined variable: imageFile in C:\xampp\htdocs\imagemachine.php on line 21

出现这些消息是因为本地范围内没有变量$imageFile只有$imageFile的属性$this