簡體   English   中英

PHP如何在另一個類中使用變量

[英]php how to use variable inside another class

我最近正在學習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變量。

所以,請告訴我如何解決此問題。

嘗試如下

<?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)使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM