Accessing a parents variable from subclass php and parent keyword?

前端 未结 2 849
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-20 16:27

I have a parent class and a subclass, the parent class has a constructer that sets a var and I would like to use that var in the subclass, I have i

2条回答
  •  天涯浪人
    2020-12-20 17:04

    First off, Parent is a reserved word. Second off, don't use var unless you're using an older version of PHP. You can use protected. You don't need to use the parent keyword to access the variable because the child class should inherit it. You can access it via $this->myVar

    EDIT to clarify

    You only need to use parent:: when accessing methods of the base class or static variables of the base class. If you try to access a non static variable of the base class you will get an error Access to undeclared static property" fatal error:

    Here's an example to get you started.

    myVar = 'a';
         }
     }
    
    class Cat extends Animal {
         public function foo() {
             echo $this->myVar;
         }
     }
    
    $cat = new Cat(); 
    $cat->foo(); 
    
    ?> 
    

    Here's a working example of this code.

提交回复
热议问题