简体   繁体   English

如何从PHP数组中存储的object调用function?

[英]How to call function from object stored in array in PHP?

I can't call / access the Id function from Product class which is stored in $products array in the foreach loop.我无法从产品 class 调用/访问 ID function,它存储在foreach循环的$products数组中。 ( $product->Id() ) ( $product->Id() )

I have tried我努力了

class Product
{
  private $id;

  public function __contruct($id)
  {
    $this->Id($id);
  }

  public function Id($value = '')
  {
    if (empty($value)) {
      return $this->id;
    } else {
      $this->id = $value;
    }
  }
}
function testArray()
{
  global $conn;

  $searchQuery = "SELECT * FROM products";
  $stmt = $conn->prepare($searchQuery);
  $stmt->execute();
  $result = $stmt->get_result();

  $products = array();

  while ($row = $result->fetch_assoc()) {
    $products[] = new Product(
      $row["id"]
    );
  }

  foreach ($products as $product) {
    print_r($product->Id());
  }

  $stmt->close();
}

You misspelled你拼错了

public function __contruct($id)

Change it to:将其更改为:

public function __construct($id)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM