Skip to content
Advertisement

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. ($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();
}

Advertisement

Answer

You misspelled

public function __contruct($id)

Change it to :

public function __construct($id)

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement