-4

this is the class:

class abc extend def {
     public static function count_all() {
        $sql = "SELECT COUNT(*) FROM " . self::$table_name; 
        $sql= $this -> conn -> prepare($sql);
        $sql -> execute();
        return $row = $sql -> fetchAll();
    }
}

after createing on veiew

$abs = new abs();
$total_count = abc::count_all();
echo $total_count;

it should echo the total count but when i echo this it show the error

Fatal error: Using $this when not in object context in

how i can solve it regards in advance.

SAR
  • 1,765
  • 3
  • 18
  • 42

2 Answers2

0

PHP allow you to access instance method by calling on Class (MyClass::instanceMethod) or calling class method on instance. But it is not be done in your code, it is not standard in Object oriented programming.

You are using $this in static method, change your method to this

 public function count_all() {
    /* Use $this->table_name for better design*/
    $sql = "SELECT COUNT(*) FROM " . self::table_name;
    $sql= $this -> conn -> prepare($sql);
    $sql -> execute();
    return $row = $sql -> fetchAll();
}

and then you can call like this

$abs = new abs();
$total_count = $abs->count_all();
echo $total_count;
Ocean
  • 2,882
  • 1
  • 18
  • 21
0

i found it this way am i doing right, regarding php development steps.

public function count_all() {
        $sql = "SELECT COUNT(*) FROM " . self::$table_name; 
        $result = $this -> conn -> prepare($sql);
        $result -> execute();
        return $total_found = $result->fetchColumn();
    }

in the view of this after calling the class.

<?php echo $class->count_all(); ?>
SAR
  • 1,765
  • 3
  • 18
  • 42