I am trying to write a class and I run into two errors.
class Foo {
protected $count;
function __construct() {
$this->count = sizeof($_POST['some_key']);
}
static function get_count() {
echo $this->count; // Problem Line
}
}
$bar = new Foo;
$bar->get_count(); // Problem Call
The problem call is on the last line. using $this in the line with the "// Problem Line" comment generates a "Using $this when not in object context" error. Using "self::count" in place of "this->count" generates an "Undefined class constant error." What could I be doing wrong?
get_count
is static. Static methods belong to the class, not the instance. As such, in a static method call, there is no this
. Similarly, you can't reference concrete member variables (such as count
) from within a static method.
In your example, I don't really understand why the static
keyword is used (since all you're doing is echoing a member variable). Remove it.
I recommend you to do the following:
class Foo {
protected $count;
function __construct($some_post) {
$this->count = sizeof($some_post);
}
function get_count() {
echo $this->count;
}
}
$some_post = $_POST['some_key'];
$bar = new Foo;
$bar->get_count($some_post);
OR:
class Foo {
protected $count;
function __construct() {
global $_POST;
$this->count = sizeof($_POST['some_key']);
}
function get_count() {
echo $this->count;
}
}
$bar = new Foo;
$bar->get_count();