Reputation: 23
QUESTION :
I Cannot figure how to use classes extends in PHP... Even reading php.net website and some examples, there is something I cannot understand or missing !
Can you please tell me what I'm doing wrong ?
Api.php
class Api
{
public static $action = '';
# public function __construct()
# {
# }
public function actionCaller ($action,$args=NULL)
{
return self::$action_($args);
}
}
ApiForum.php
class ApiForum extends Api
{
#private static $forum;
public function __construct()
{
#self::$forum = new Api();
}
private function getPost ($args)
{
echo 'executed.';
#return "get forum post $args";
}
}
test.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', true);
require_once('config.php');
require_once('classes/_Autoload_.php');
echo Api::actionCaller('forum')->getPost();
The result :
PHP Fatal error: Call to a member function getPost() on a non-object in /var/www/html/api.example.com/test.php on line 10
Please be clement with me ;)
CL
ANSWER:
Okay it's working now ! Thanks to all... There was more than one problem, here is the result :
Api.php
class Api
{
# public function __construct()
# {
# }
public function actionCaller ($action,$args=NULL)
{
return self::$action($args);
}
public function forum ()
{
return new ApiForum();
}
}
ApiForum.php
class ApiForum extends Api
{
# public function __construct()
# {
# }
public static function getPost ($args)
{
echo 'executed.';
}
}
test.php
error_reporting(E_ALL);
ini_set('display_errors', true);
require_once('config.php');
require_once('classes/_Autoload_.php');
echo Api::actionCaller('forum')->getPost('test');
I feel I need some more readings about classes and objects scopes ... :)
Upvotes: 2
Views: 509
Reputation: 2093
Just switch your "getPost" method declaration for this:
static function getPost($args){
A private method means only that class can execute that method. A static method means that it can be called without an object being instantiated, like what you're trying to do with the double colon eg. class::method(args)
.
Just for completeness sake, a public function is the middle ground. An object has to be instantiated for you to call it (via $object->method(args)
), but it is available to any file that has imported that class
Just a side note: I'd also like to add that for a method to be used as a static method, it still needs to be "included"! I apologise for the use of the word "imported", I've been playing around in a lot of other languages recently!
Upvotes: 1