Ben
Ben

Reputation: 62366

PHP Requiring specific type cohersion

With the below code, $quantity is assumed to be an integer but I'm not doing any checking against it to require it to be so.

public function addProduct($product, $quantity) {

The below code will require it to be an integer, BUT if $quantity = '1'; it'll fail because it's a string. Is it possible for me to force $quantity to come through as an integer in this function, or do I HAVE to do $object->addProduct($product, (int) $quantity); ?

public function addProduct($product, int $quantity) {

Lastly, is it possible for me to flag $product as either a string or an integer, but if it's passed an object it'll break (without writing an is_object() check)

Upvotes: 0

Views: 97

Answers (5)

Mob
Mob

Reputation: 11098

You cast the type to an integer. You should always cast to the appropriate data type for all your user-inputted values.

$quantity = (int) $quantity;

$quantity is now an integer

Upvotes: 0

DC.
DC.

Reputation: 41

To make sure that param gets in as an integer, simply add this line at the very begining of your method:

public function addProduct($product, $quantity) {
  $quantity = intval( $quantity );

  // your code here
}

Upvotes: 1

KingCrunch
KingCrunch

Reputation: 131861

You can cast the value within the method itself

$quantity = (int) $quantity;

Upvotes: 0

grunk
grunk

Reputation: 14938

Type hinting is not available for primitive type. The only solution you have in this case is to use intval() or is_int() on your param :

public function addProduct($product, $quantity) {
 $quantity = intval($quantity);
}

Upvotes: 2

Manse
Manse

Reputation: 38147

You must specify the type of an argument as either an Object or an Array, ie it cant be both -> http://php.net/manual/en/language.oop5.typehinting.php

Upvotes: 1

Related Questions