TechnoDiver Posted September 1, 2021 Share Posted September 1, 2021 I have this static method: public static function getIDByCategory($category) { $query = "SELECT top_cat_id FROM top_categories WHERE top_cat_title=?"; $stmt = self::$conn->prepare($query); <-- line 89 from the error message $stmt->execute([$category]); $row = $stmt->fetch(PDO::FETCH_ASSOC); $cat_id = $row['top_cat_id']; return $cat_id; } I'm calling it like this from a different class: $cat_id = Category::getIDByCategory($category); and I'm getting this error: Quote Fatal error: Uncaught Error: Access to undeclared static property Category::$conn in /opt/lampp/htdocs/qcic/assets/class/Category.php:89 I feel like I've followed all the rules. Could someone breakdown the mechanics of what is happening here? Quote Link to comment https://forums.phpfreaks.com/topic/313646-static-methods/ Share on other sites More sharing options...
Strider64 Posted September 1, 2021 Share Posted September 1, 2021 (edited) Why don't you just extend the child class? Does it work in the parent class? If it doesn't then there is something wrong with self::$conn You might be initializing the database connection before it is called? Edited September 1, 2021 by Strider64 Quote Link to comment https://forums.phpfreaks.com/topic/313646-static-methods/#findComment-1589576 Share on other sites More sharing options...
TechnoDiver Posted September 1, 2021 Author Share Posted September 1, 2021 42 minutes ago, Strider64 said: Does it work in the parent class? If it doesn't then there is something wrong with self::$conn this static method is in a class with public methods and $this->conn is working fine. It's a quick method to take care a of quick need I don't want to have to instantiate an object just to use this quick method. Is there anything else I have to do inside the class to make it work as self::$conn? Like I said $this->conn is working fine everywhere else in the class Quote Link to comment https://forums.phpfreaks.com/topic/313646-static-methods/#findComment-1589577 Share on other sites More sharing options...
kicken Posted September 1, 2021 Share Posted September 1, 2021 You can't get just decide to access an instance-level property as if it were a static property. The whole thing with static properties and methods is that there is no instance so instance-level stuff cannot be used. You either need to setup a static property for your connection or pass the connection into your static method as a parameter. Quote Link to comment https://forums.phpfreaks.com/topic/313646-static-methods/#findComment-1589578 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.