简体   繁体   English

试图了解PHP OOP

[英]Trying to understand 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. 我正在尝试从父类中的方法访问Bar::$some_var Where Bar::$some_var is defined in it's constructor. 其中Bar::$some_var在其构造函数中定义。

I've tried using self::$some_var and static::$some_var in Foo::hello() but neither worked. 我试过在Foo::hello()使用self::$some_varstatic::$some_var ,但都没有用。 Do I have to make $some_var static ? 我必须使$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. private使成员变量在类外部不可用。 You need to use protected to allow extending classes to have access to that variable. 您需要使用protected来允许扩展类访问该变量。

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. 无论如何,在您的代码中,问题是$ some_var的可见性。 It has to be almost protected, public will also work 它必须受到几乎保护,公众也将工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM