php 构造函数未定义属性

标签 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 对象并调用它的 sayth() 方法。这些参数来自 ui 文件中的表单。

在 imageMachine 中,我显然想对图像做一些事情,但这不是问题。目前,当我只想让实例从构造函数中简单地保护参数($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':

最佳答案

我将逐条解释错误消息:

// 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。它正在查找名为 $this$imageFile 值的属性,但该属性不存在(原因见上文)。

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

// 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,只有 $this 的属性 $imageFile

关于php 构造函数未定义属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48464564/

相关文章:

php - 刷新 Woocommerce 中购物车事件的自定义组件

php - 与mysql数据库中的其他数据分开保存的链接

javascript - 级联对象声明给出了第二个对象的未定义 typeof

java - JFrame 类型的 createGUI() 方法未定义

php - 如何用PHP获取年份?

php - Laravel - 在子文件夹中返回 View

java - 如何从参数化构造函数(Java)调用构造函数?

c++ - 是否保证在定义变量时准确调用构造函数?

c# - : base()代码是什么

c++ - undefined symbol