从子类php和父关键字访问父变量? [英] Accessing a parents variable from subclass php and parent keyword?

查看:179
本文介绍了从子类php和父关键字访问父变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个父类和一个子类,父类有一个构造函数设置 var ,我想使用 var 在子类中,我有它的工作,但我很困惑的关键字 parent



Example

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

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

$ c> myVar ,但我应该使用关键字 parent ,当我收到一个错误,例如,

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

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


解决方案

关闭,父级是保留字。第二,不要使用 var ,除非你使用的是旧版本的PHP。你可以使用protected。您不需要使用parent关键字来访问变量,因为子类应该继承它。您可以通过 $ this-> myVar



EDIT / p>

当访问基类或 static的方法时,只需使用 parent :: 基类的变量。如果你尝试访问基类的非静态变量,你会得到一个错误访问未声明的静态属性致命错误:



这是一个让你开始的例子。

 <?php 
class Animal {
protected $ myVar;
public function __construct(){
$ this-> myVar ='a';
}
}

Cat extends Animal {
public function foo(){
echo $ this-> myVar;
}
}

$ cat = new Cat );
$ cat-> foo();

?>

这是此代码的工作示例。


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';
     }
 }

解决方案

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.

这篇关于从子类php和父关键字访问父变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆