Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.0k views
in Technique[技术] by (71.8m points)

oop - Accessing a parents variable from subclass php and parent keyword?

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 it working but am getting confused by the keyword parent?

Example

 class Sub extends Parent {
     public function foo() {
         echo $this -> myVar;
     }
 }

 class Parent {
     var $myVar;
     public function __construct() {
          $this -> myVar = 'a';
     }
 }

This worked and I get the value of myVar, but am I supposed to be using the keyword parent and when I do I get an error, example,

 class Sub extends Parent {
     public function foo() {
         echo parent -> myVar;
     }
 }

 class Parent {
     var $myVar;
     public function __construct() {
          $this -> myVar = 'a';
     }
 }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

<?php
class Animal{
     protected $myVar;
     public function __construct() {
          $this->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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...