Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force arguments to be integer/string

Tags:

I'd like my functions to expect strings/integers or throw a fit, like:

warning: preg_match() expects parameter 2 to be string

However for this function

public function setImage($target, $source_path, integer $width, integer $height){... 

I get:

Argument 4 passed to My_Helper_Image::setImage() must be an instance of integer, integer given

But:

function(array $expectsArray) 

works as I expect, how would I achieve the same effect as with integers and strings?

Big Update

PHP 7 now supports Scalar Type Hinting

function increment(int $number) {      return $number++; } 
like image 296
Moak Avatar asked Mar 25 '11 08:03

Moak


People also ask

How do you pass an integer into a string array?

Object ,you can simply pass Object[] as second argument and you pass argument(String,Int,....etc) whatever you want.

How to make python return an integer?

The int() function converts the specified value into an integer number. The int() function returns an integer object constructed from a number or string x, or return 0 if no arguments are given. A number or string to be converted to integer object. Default argument is zero.

Can integers be strings?

Integer can be converted to String, but String cannot be converted to Integer. Integer is a numeric value, while String is a character value represented in quotes.


1 Answers

Scalar TypeHints are available as of PHP 7:

Scalar type declarations come in two flavours: coercive (default) and strict. The following types for parameters can now be enforced (either coercively or strictly): strings (string), integers (int), floating-point numbers (float), and booleans (bool). They augment the other types introduced in PHP 5: class names, interfaces, array and callable.

There is no Type Hints for scalars before PHP7. PHP 5.3.99 did have scalar typehints but it wasn't finalised at that point if they stay and how they will work then.

Nevertheless, there is options for enforcing scalar arguments before PHP7.

There is a couple of is_* functions that let you do that, e.g.

  • is_int — Find whether the type of a variable is integer
  • is_string — Find whether the type of a variable is string
  • more

To raise a Warning, you'd use

  • trigger_error — Generates a user-level error/warning/notice message

with an E_USER_WARNING for $errorType.

Example

function setInteger($integer) {     if (FALSE === is_int($integer)) {         trigger_error('setInteger expected Argument 1 to be Integer', E_USER_WARNING);     }     // do something with $integer } 

Alternative

If you want to use Scalar Type Hints desperately, have a look at

  • http://edorian.github.io/2010-03-30-typehints-hack-for-literal-values-in-php/

which shows a technique for enforcing scalar typehints via a custom Error Handler.

like image 71
Gordon Avatar answered Nov 04 '22 21:11

Gordon