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

时间:2015-03-26 14:03:32

标签: php

这些天我学习php。我在下面有一个查询:

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 ), 

}

我在类中而不是在函数内部声明$ b因为我需要在我的php文件中的许多地方使用$ b变量。

所以,请告诉我如何解决这个问题。

2 个答案:

答案 0 :(得分:0)

尝试如下

<?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";
?>

希望它会帮助你

答案 1 :(得分:0)

1。)使用public代替var 2.)当你扩展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
相关问题