簡體   English   中英

如何在PHP中定義一個供兩個不同類使用的函數?

[英]How do I define a function in PHP for use by two different classes?

我有兩個PHP類,並且想要做這樣的事情:

class Class1
{
    $x=3;
    coolFunction($x);
    }

class Class2
{
    $y = 7;
    coolFunction($y);
    }

我試着做:

public function coolFunction($z)
{
    $youGetTheIdea = 10;
    return $z + $youGetTheIdea;
    }

但是PHP不喜歡那樣,在這一點上我很茫然。 如何使兩個類都可以訪問該函數,或者有沒有辦法做類似的事情? 我來自Python背景,因此您可以做的一切都可以幫助我理解PHP。

您可以使用特質

trait TraitCoolFunction {
    private function coolFunction($z) {
        $youGettheIdea = 10;
        return $z + $youGetTheIdea;
    }
}

使用方法:

class Class1 {
    use TraitCoolFunction;
    /* other stuff here */
}

需要PHP 5.4或更高版本。

您只能為類方法指定publicprivate 類外的普通函數僅通過function定義:

function coolFunction($z)
{
    $youGetTheIdea = 10;
    return $z + $youGetTheIdea;
}

暫無
暫無

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

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