Vishal Khialani
Vishal Khialani

Reputation: 2587

pls explain the argument in this function

please see below code function isInMatchingSet(Card $card) is taking "card $card" usually I have seen "$one,$two" when I code never a static value like "Card" so what is card here ? I am guessing its the class name. I could not find a good explanation on this so I thought of asking here.

<?php

/**
 * Models an individual card.
 */
class Card
{
    /**
     * @var string
     */
    private $number;

    /**
     * @var string
     */
    private $suit;

    /**
     * @param string $number
     * @param string $suit
     */
    public function __construct($number, $suit)
    {
        $this->number = $number;
        $this->suit   = $suit;
    }

    /**
     * @return string
     */
    public function getNumber()
    {
        return $this->number;
    }

    /**
     * @return string
     */
    public function getSuit()
    {
        return $this->suit;
    }

    /**
     * Returns true if the given card is in the same set
     * @param Card $card
     * @return bool
     * @assert (new Card(3, 'h'), new Card(3, 's')) == true
     * @assert (new Card(4, 'h'), new Card(3, 's')) == false
     */
    public function isInMatchingSet(Card $card)
    {
        return ($this->getNumber() == $card->getNumber());
    }
}

Upvotes: 1

Views: 48

Answers (1)

Pekka
Pekka

Reputation: 449595

This is called type hinting. It was introduced in PHP 5.

PHP 5 introduces type hinting. Functions are now able to force parameters to be objects (by specifying the name of the class in the function prototype), interfaces, arrays (since PHP 5.1) or callable (since PHP 5.4). However, if NULL is used as the default parameter value, it will be allowed as an argument for any later call.

Examples:

// Array — expects an array
function test(Array $array) {
}

// Interface — expects an object of a class implementing the given interface
function test(Countable $interface) {
}

// Class — expects an object of that class (or any sub-classes)
function test(Exception $object) {
}

// Callable  — expects any callable object
function test(callable $callable) {
}

Upvotes: 4

Related Questions