[英]What does the `use <ClassName>;` syntax mean in the class body in PHP?
在PHPUnit文檔中,我遇到了一些我不熟悉的PHP語法。
https://phpunit.readthedocs.io/en/7.3/database.html#asserting-the-result-of-a-query
<?php
use PHPUnit\Framework\TestCase;
use PHPUnit\DbUnit\TestCaseTrait;
class ComplexQueryTest extends TestCase
{
use TestCaseTrait;
public function testComplexQuery()
{
$queryTable = $this->getConnection()->createQueryTable(
'myComplexQuery', 'SELECT complexQuery...'
);
$expectedTable = $this->createFlatXmlDataSet("complexQueryAssertion.xml")
->getTable("myComplexQuery");
$this->assertTablesEqual($expectedTable, $queryTable);
}
}
use TestCaseTrait;
是我不明白的那條線。 我知道頂部的use
代用名允許在沒有完整名稱空間的情況下按名稱使用該類,但是我不知道它在做什么。 搜索use
的PHP yeilds有關該功能的效果。
易於解釋(不是主要內容,而是作為示例):它用於變量和方法,您必須反復編寫。 沒有復雜的邏輯!
特征:
trait Name {
protected $name;
getName() {
return $this->name;
}
setName($name) {
$this->name = $name;
}
}
class test {
use Name;
/* In background it looks like that (without comment ;) */
//protected $name;
//getName() {
// return $this->name;
//}
//setName($name) {
// $this->name = $name;
//}
}
10需要這些變量和方法的其他類,可以使用它們。
並且在此測試案例中,大多數時候您需要使用相同的方法,這就是為什么它們只包含這樣的方法。
將其留給php.net上的注釋進行澄清。 以下注釋使我想到了此功能的術語“特征”。 (我應該猜出這個名字是正確的類型。) https://secure.php.net/manual/zh/language.namespaces.importing.php#119919
引用手冊:
從PHP 5.4.0開始,PHP實現了一種稱為Traits的代碼重用方法。
特性是一種在PHP等單一繼承語言中重用代碼的機制。 特性旨在通過使開發人員能夠在生活在不同類層次結構中的幾個獨立類中自由重用方法集,從而減少單一繼承的某些限制。 以減少復雜性並避免與多重繼承和Mixins相關的典型問題的方式定義特征和類的組合的語義。
特性與類相似,但僅用於以細粒度且一致的方式對功能進行分組。 無法單獨實例化特性。 它是對傳統繼承的補充,可以實現行為的橫向組合; 也就是說,類成員的應用無需繼承。
我從未聽說過此功能,很有趣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.