在函数参数中转换数据类型?

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

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.

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

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

}

data(123);

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"

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);