PHP错误:缺少参数1,即使我传递变量
问题描述:
即使错误var_dump
仍然有效。一切似乎都奏效,但我得到了这两个重复4次的错误。PHP错误:缺少参数1,即使我传递变量
错误:
Warning: Missing argument 1 for Product::__construct() in Product.php on line 13
Notice: Undefined variable: attributes in Product.php on line 14
的index.php:
$products = $query->selectAll('products');
foreach ($products as $product) : ?>
<li><?= $product->title; ?></li>
<?php endforeach;
$arr = [
'type' => 'Furniture',
];
$furniture = new Product($arr);
var_dump($furniture->type);
Product.php:
class Product
{
public $type;
public function __construct($attributes) { // line 13
$this->type = $attributes['type']; // line 14
}
}
编辑:
我有return $query->fetchAll(PDO::FETCH_CLASS, "Product");
从以前的测试,只是从它删除“产品”。
$products = $query->selectAll('products');
foreach ($products as $product) : ?>
<li><?= $product->title; ?></li>
<?php endforeach;
全选()方法:
public function selectAll($table)
{
$query = $this->pdo->prepare("SELECT * FROM `$table`");
$query->execute();
return $query->fetchAll(PDO::FETCH_CLASS, "Product");
}
答
如果你想PDO创建一个自定义当我删除注释掉的这部分的index.php
错误都不见了对象实例你必须传递构造函数参数。在PDOStatement::fetchAll()这是第三个参数:
public array PDOStatement::fetchAll ([ int $fetch_style [, mixed $fetch_argument [, array $ctor_args = array() ]]])
[...]
ctor_args
Arguments of custom class constructor when the fetch_style parameter is PDO::FETCH_CLASS.
如果$属性是数组类型或不是你还没有定义,请定义,你不会得到这些警告 – Rahul
我无法重现错误。你确定你没有在没有变量的情况下在更早的时候实例化Product? @Rahul类型暗示不会解决这个问题。 –
您按预期显示的代码没有任何警告或通知。 –