casting data type in function arguments?

Does anyone know why it fails?

<?php 
function data((string)$data)
{
echo $data;

}

data(123);

Here is the error:

Parse error: syntax error, unexpected T_STRING_CAST, expecting '&' or T_VARIABLE in x.php on line 3

Upvotes: 3

Views: 372

Answers (4)

Mr. Pyramid
Mr. Pyramid

Reputation: 3935

You are not allowed to typecast like this instead you can hint the type of your argument using the concept of type hinting read more about type hinting

<?php 
function data(string $data)
{
echo $data;

}

data(123);

or if you are fine with this you can use like this

<?php 
function data($data)
{
echo (string) $data;

}

data(123);

Upvotes: 0

JParkinson1991
JParkinson1991

Reputation: 1286

What your are trying to do is called: Type Hinting.

That is allowing a function or class method to dictate the type of argument it recieves.

Static type hinting was only introduced in PHP7 so using a version greater than that you can achieve whay you want with the following:

<?php

function myFunction(string $string){
    echo $string;
}

Now any non string argument passed to myFunction will throw an error.

Upvotes: 1

Ren&#233; H&#246;hle
Ren&#233; H&#246;hle

Reputation: 27295

That should work:

<?php 
function data(string $data) {
    echo $data;
}

data(123);

But you have to use PHP7. I have tested that code with PHP7.

Output: string(3) "123"

Upvotes: 0

underscore
underscore

Reputation: 6887

You cant cast when parsing arguments to the function. Do it inside the function

function data($data)
{
echo (string) $data;

}

data(123);

Upvotes: 0

Related Questions