试图理解PHP OOP

I'm wondering why the following code won't print out anything. I'm trying to access Bar::$some_var from method in parent class. Where Bar::$some_var is defined in it's constructor.

I've tried using self::$some_var and static::$some_var in Foo::hello() but neither worked. Do I have to make $some_var static?

class Foo {

    private $some_var;

    public function __construct() {
        $this->some_var = 5;
    }

    public function hello() {
        print $this->some_var;
    }
}

class Bar extends Foo {

    public function __construct() {
        $this->some_var = 10;
    }
}

$bar = new Bar();
$bar->hello();

Thanks in advance.

private makes a member variable unavailable outside of a class. You need to use protected to allow extending classes to have access to that variable.

protected $some_var;

See Visibility

Your class variable cannot be private if you would like your child class to access it. Try protected instead and it should work!

  • :: operator is used to access class items (constants, static variables, static methods)
  • -> operator is used to access object items (non static properties and methods)

anyway in your code the problem is visibility of $some_var. It has to be almost protected, public will also work