简体   繁体   English

PHP如何在另一个类中使用变量

[英]php how to use variable inside another class

Iam learning php these days. 我最近正在学习php。 I have one query below: 我在下面有一个查询:

class A {

var $a;

}

class B extends A{

var $b = $a; //here its showing me error, i even tried as '$this->$a' but still showing error. so, how do I use $a in class B? ( instead of using in a function ), 

}

I am declaring $b just inside class instead of inside a function because I need to use $b variable in many places inside my php file. 我声明$ b只是在类内部,而不是在函数内部,因为我需要在我的php文件中的许多地方使用$ b变量。

So, please tell me how to fix this. 所以,请告诉我如何解决此问题。

try like below 尝试如下

<?php

class firstname 
{
   public static $name='Your First Name';
}
class lastname
{
   public static $last='Your Last Name';
}
class Fullname
{

     public static function staticValue() {
        return firstname::$name."--".lastname::$last;
    }
}

print Fullname::staticValue() . "\n";
?>

hope it will help you 希望对你有帮助

1.) use public instead of var 2.) when you extending a class, you have got access to properties of this parent. 1)使用public的,而不是var 2)当你扩展a类,你必须进入这个父的性能。 So you don't need to declare $b, you can just use $this->a 因此,您无需声明$ b,只需使用$this->a

class a {
    $a = 'test';
}

class b extends a {
   public function get() {
       echo $this->a;
   }
}

$b = new b;
$b->get(); // prints test

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

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