top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration

Facebook Login
Site Registration

How to read static variables in child-classes (using PHP)?

+1 vote

Why I can't read static variables of a child class, even so the variable is protected or public?

Here's what I tried:

class A {
 protected static $foo = "bar";

class B {
 public function readFoo() {
 return self::$foo;

When now calling B::readFoo, I get the following error:

var_dump((new B())->readFoo());

PHP Fatal error: Access to undeclared static property: B::$foo in php shell code on line 1
PHP Stack trace:
PHP 1. {main}() php shell code:0
PHP 2. B->readFoo() php shell code:1

Fatal error: Access to undeclared static property: B::$foo in php shell
code on line 1

Call Stack:
 86.2643 231224 1. {main}() php shell code:0
 86.2666 231352 2. B->readFoo() php shell code:1
posted Dec 16, 2013 by Sanketi Garg

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote

You forgot to extend B from A

answer Dec 16, 2013 by Bob Wise
Similar Questions
+5 votes

You can find three principal uses for the static. This is a good way how to start your answer to this question. Let’s look at the three principal uses:

  1. Firstly, when you declare inside of a function: This retains the value between function calls

  2. Secondly, when it is declared for the function name: By default function is extern..therefore it will be visible out of different files if the function declaration is set as will be invisible for outer files

  3. And lastly, static for global parameters: By default you can use global variables from outside files When it’s static global..this variable will be limited to within the file.

is this right ?

Contact Us
+91 9880187415
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Karnataka INDIA.