簡體   English   中英

如何將公共值從父 class 傳遞給 PHP 中的子 class?

[英]How to pass public value from parent class to child class in PHP?

我只是在 PHP 中更深入地了解 OOP,但還不是專家。 我還是個初學者。 我有個問題。 我想將公共值從父 class 傳遞給子 class。 但我無法得到它。 我試圖在 google 和 stackoverflow 中找到答案,並嘗試按照說明進行操作,但沒有奏效。

我的代碼如下:

class A
{
    public $arrayperk;
    public $nilai;
    
    function __construct()
        {
            $this->nilai='This is bad';
        }
    function testParent()
        {
            return $this->arrayperk;
        }
    function testA()
        {
            return number_format(1000); 
        }
}

class B extends A
{
    function  coba()
        {
            return $this->testParent();
        }
    function  coba2()
        {
            return $this->testA();
        }
    function coba3()
        {
            return $this->nilai;
        }
}

問題是我想將$arrayperk 的值傳遞給class B內的 function 。 但它根本沒有用。

我的代碼如下:

$arrayperk=Array( 1 => 'array1', 2 => 'array2');
$class_a=new A();
$class_a->arrayperk=$arrayperk;
$class_b=new B();

print_r($class_a->testParent()); //return array as needed.
print_r($class_b->coba()); //return nothing although it calls the parent class, and the parent work correctly if it is called like above. This is what I want to get and the problem I face.
echo $class_b->coba2(); //return 1,000 and it access the parent function
echo $class_b->coba3(); //return This is bad as written at parent class.

如您所見,問題出在

$class_b->coba()

即使我正確地將其調用給父 class,它也沒有給出任何結果,但是在訪問父 class function 時,其他測試工作正常。

我什至無法在 class B 中傳遞$this->arrayperk 。它什么也不返回。 我錯過了什么? 我無法在父 class 中同時獲得$this->arrayperk和 function。

請幫忙。 謝謝。

您正在實例化 2 個不同的類, $class_a$class_b 您只是為 $ $arrayperk設置$clas_a

$class_a=new A();
$class_a->arrayperk=$arrayperk;
$class_b=new B();

在這里,當 $class_b 被實例化時,你沒有給它任何屬性。 一個簡單的解決方法是只分配屬性:

$class_b->arrayperk = $arrayperk;

即使您繼承了父方法,實際屬性$arrayperk在您的情況下是空的,因此您需要為每個實例單獨設置它。

Inheritance 意味着您繼承父 class 的方法,但每個實例都作為一個單獨的單元運行。

如果你這樣做

$class_c = new B();
var_dump($class_c->arrayperk);

該值最終也將是 NULL

如果你 var_dump 你的值而不是打印也有幫助,因為在這種情況下你會看到 arrayperk 的值是 NULL。

暫無
暫無

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

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