Reputation: 303
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
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
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
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
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