I am now trying this out for more 12 hours and am really frustrated cause it does not work.
I have two classes Book
and Comment
. Each Book has multiple Comments. I want to return a specific book with its n-Comments. For this, i created both classes, cause each class should also have additional operations like Add, Delete, Update etc.
My problem is, when i call a static function in Comment class from a non-static function from the book class it does not work:
$result = Comment::GetCommentByBookId($id);
Curious thing is, when i change the static function GetCommentByBookId
in the Comment class to a non-static function, and change the line in the GetBookById function to
$c = new comment;
$result = $c->getCommentByBookId(1);
it works! But why does it not work when i try to call static function?
These are the classes:
Book
<?php
require_once ("class/DBController.php");
require_once ("class/Comment.php");
class Book {
private $db_handle;
function __construct() {
$this->db_handle = new DBController();
}
function GetBookById($id) {
$query = "SELECT * FROM book WHERE id = ?";
$paramType = "i";
$paramValue = array(
$id
);
$c = new comment;
$result = $c->getCommentByBookId(1);
//$result = Comment::GetCommentByBookId($id);
return $result;
}
function GetAllBooks() {
$query = "SELECT * FROM book";
$result = $this->db_handle->runBaseQuery($query);
return $result;
}
}
?>
Comment
<?php
require_once ("class/DBController.php");
class Comment {
private $db_handle;
function __construct() {
$this->db_handle = new DBController();
}
static function GetCommentByBookId($id) {
echo "Entered 'GetCommentByBookId'<br>";
$query = "SELECT * FROM comment WHERE book_id = ?";
$paramType = "i";
$paramValue = array(
$id
);
echo "Pre-Ex 'GetCommentByBookId'<br>";
$result = $this->db_handle->runQuery($query, $paramType, $paramValue);
echo "Executed successfully 'GetCommentByBookId'<br>";
return $result;
}
}
?>
2
Answers
If you don’t instantiate a Comment instance, you can’t access $this->db_handle.
You can consider doing like below:
Question: But why does it not work when i try to call static function?
Answer: Because when you call a static method outside the class then construct of that class does not run and hence if you are calling any other property which is dependent on construct class you will get the error.
In your case when you called
static function GetCommentByBookId($id)
in that static method you are calling$result = $this->db_handle->runQuery($query, $paramType, $paramValue);
now as construct does not ran hencethis->handle
did not instanciated the class when you called static method hence you get the error for$this->db_handle->runQuery
**Example**
I have reconstructed your code you explain what i mean. Please have a look at the code and the result image.
Result:
If you have any query/issue or find something incorrect please comment.