php - Fatal error: Uncaught ArgumentCountError: Too few arguments to function PostManager::__construct()

Viewed 2606

Hi guys I'm new to php and there is something weird I don't understand. All the functions inside the class is working.

But now I want to get this information when I create new instance

I try to add __construct and use the same functions but it get the following error :

Fatal error: Uncaught ArgumentCountError: Too few arguments to function PostManager::__construct(), 0 passed and exactly 2 expected

The thing is that if I try to echo/var_dump the values from the __construct its working. I did find around stackoverflow some results but nothing really helpful for my case or I just understood it wrong. I used both static:: and self:: but got the same results. please let me know if I need to add more info.

the files :

index.php :

<?php
require "Curl.php";
require "Proccessor.php";
require "User.php";
require "PostManager.php";
$conn = require 'db.php';

// this is work $post = PostManager::getPostInfo($conn, 3); 
   // **this is not work** $post = new PostManager($conn, 3);

PostManager.php :

<?php
class PostManager
{
    public $postId;
    public $conn;
    public function __construct($conn, $postId)
    {

        $this->postId = $postId;
        $this->conn = $conn;
       //here I get the error =>  static::getPostById($conn, $postId);
        
    }

    public static function getPostInfo($conn, $postId)
    {
        $post = static::getPostById($conn, $postId);
        $user = User::getByID($conn, $post->user_id);
        $comments = static::getCommentsByUserID($conn, $post->id);
        $post_info = (object) ["post" => $post, "user" => $user, "comments" => $comments];
        return $post_info;
    }

    public static function getPostById($conn, $id)
    {
        $sql = "SELECT post.*
              FROM post
              WHERE id = :id";
        $stmt = $conn->prepare($sql);
        $stmt->bindValue(':id', $id, PDO::PARAM_INT);
        $stmt->setFetchMode(PDO::FETCH_CLASS, 'PostManager');
        if ($stmt->execute()) {
            return $stmt->fetch();
        }
    }

    public static function getCommentsByUserID($conn, $postId)
    {
        $sql = "SELECT comment.*
      FROM comment
      WHERE post_id = :post_id";
        $stmt = $conn->prepare($sql);
        $stmt->bindValue(':post_id', $postId, PDO::PARAM_INT);
        $stmt->setFetchMode(PDO::FETCH_CLASS, 'PostManager');
        if ($stmt->execute()) {
            return $stmt->fetch();
        }
    }

}
1 Answers

Try this:

$stmt->setFetchMode(PDO::FETCH_CLASS, 'PostManager', array($conn, $postId));

You forgot to pass the parameters here.

This is the signature you wanna use:

public PDOStatement::setFetchMode(int $mode = PDO::FETCH_CLASS, string $class, ?array $constructorArgs): bool

As you can see if the Ctor has args then you need to pass them as another parameter
array $constructorArgs

Related