문제

public function setAlbumTable(AlbumTable $albumTable)
{
$this->albumTable = $albumTable;
return $this;
}
.

첫 번째 매개 변수 (BTW 매개 변수가 아님)에 대해 이야기하고 있습니다. 데이터 유형처럼 보입니까?그게 뭐야?일정한 ?Zend Framework 2 에서 앱을 개발하려고 할 때이를 만난다.

도움이 되었습니까?

해결책

This is PHP's type hinting. It means that the first parameter to this function - $albumTable - must be an instance of the AlbumTable class or a class that inherits from it.

class Car {}

class BlueCar extends Car {}

function drive_the_car(Car $car) {}

drive_the_car(42); // error, first parameter must be an instance of Car

drive_the_car(new stdClass()); // error

drive_the_car(new Car()); // works

drive_the_car(new BlueCar()); // works

다른 팁

The piece of code you're showing is an example of dependency injection via setter method. The setter is passed an instance of AlbumTable and assignes this instance to a class field.

Your method is passed ONLY ONE parameter: $albumTable.

The AlbumTable before the parameter is a type hint and makes sure that only a instance of AlbumTable or a deriving class can be passed to the setter.

It forces the actual parameter ($albumTable) to be an instance of AlbumTable class. PHP will give a fatal error if anything else is passed to the function.

This is useful so you don't have to check what type of variable/object you received in order to make use of it's functions and properties.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top