Reputation: 57
<?php
class getCatlist
{
function catList()
{
global $db;
try {
$stmt2 = $db->query("SELECT c.id, c.name, c.slug, c.parent, COUNT(b.catID) AS Total FROM categories c LEFT JOIN blog_post_cats b ON b.catID = c.id GROUP BY c.id HAVING Total > 0");
$row_count = $stmt2->rowCount();
if ($row_count >= 0) {
$rows = $stmt2->fetchAll(PDO::FETCH_ASSOC);
}
} catch (PDOException $e) {
echo $e->getMessage();
}
$items = $rows;
$id = '';
echo "<ul>";
foreach ($items as $item) {
if ($item['parent'] == 0) {
echo "<li><a href='category-".$item['slug']."'>".$item['name']." (".$item['Total'].")</a>";
$id = $item['id'];
sub($items, $id);
echo "</li>";
}
}
echo "</ul>";
}
function sub($items, $id){
foreach ($items as $item) {
if ($item['parent'] == $id) {
echo "<ul>";
echo "<li><a href='category-".$item['slug']."'>".$item['name']." (".$item['Total'].")</a></li>";
sub($items, $item['id']);
echo "</ul>";
}
}
}
}
?>
I call this class with these function catList()
and function sub($items, $id)
with that:
<?php
$cat = new getCatlist();
$cat->catList();
$cat->sub();
?>
But server give me this error: Call to undefined function sub() . So what's wrong with my code? What I miss? And how to I define this: function sub().
I tried and search this calling methods from class things but I didn't solve my problem. So I hope I find in here the solution. Thanks.
Upvotes: 1
Views: 4423
Reputation: 7409
The same error can be reproduced with a smaller bit of code like this:
<?php
class Foo{
public function baz(){
bar();
}
public function bar(){
echo "boo";
}
}
$foo = new Foo();
$foo->baz();
PHP Fatal error: Uncaught Error: Call to undefined function bar() in /home/hpierce/PhpstormProjects/Temp/addNumbers.php:5
That error is talking about the reference to bar()
on 5th line, stored within the class, not the method call on the Foo object:
class Foo{
public function baz(){
bar(); //<--- This!
}
//...
}
$foo->baz(); // <-- NOT this.
In PHP, referencing a method of a class from within the class requires the function call to be prefixed with $this->
. Without using that PHP is attempting to use a function defined in the global namespace, where there isn't a function named sub()
.
This is different from languages like Java, where functions can be referenced without an explicit self reference.
The above code can be fixed like this:
<?php
class Foo{
public function baz(){
$this->bar();
}
public function bar(){
echo "boo";
}
}
$foo = new Foo();
$foo->baz();
Upvotes: 4