This question already has answers here:
How to resolve "must be an instance of string, string given" prior to PHP 7?
(9 answers)
Closed 10 years ago.
I'm trying to use this method :
public function setMessage(string $message){
$this->message = $message;
}
Then I get this error :
Catchable fatal error: Argument 1 passed to notifier::setMessage()
must be an instance of string, string given
Apparently PHP is interpreting string as class name. Is there a look like solution to make that kind of declaration ?
Typehinting can only be used on objects, with the exception of arrays.
From the Manual:
Type hints can not be used with scalar types such as int or string. Traits are not allowed either.
PHP is a loosely typed language, it doesn't really care about the type and will guess anyways. You can only limit variables to classes at the function declaration, so remove the string and everything will be fine. :)
If you really want to be sure it is a string use gettype() or cast the variable to a string.
Note (from type-juggline on PHP.net):
Instead of casting a variable to a string, it is also possible to
enclose the variable in double quotes.
$foo = 10; // $foo is an integer
$str = "$foo"; // $str is a string
$fst = (string) $foo; // $fst is also a string
Related
This question already has answers here:
What is the purpose of the question marks before type declaration in PHP7 (?string or ?int)?
(4 answers)
Closed 1 year ago.
I was doing some research but wasn't able to find an answer (probably beacause I did not searched it right)
Consider this piece of code:
public function foo(?array $optionalParam);
And then this one:
public function foo(array $optionalParam = null);
What differs between them? Using PHPstorm I noticed that when I use the ?, it creates a PHPdoc and mark the variable type as type|null. But when I call the function without that argument, PHP screams on my face "you kidding me? where is $optionalParam". In the other side, I managed to use with no problems the =null option.
Sorry if this question is too simple, but i did not find any answers online.
First of all, the ? goes before the type, not after... other than this:
Using
public function foo(?array $optionalParam);
you are forced to pass something, that can be either null or an array, infact:
<?php
function foo(?array $optionalParam){
echo "test";
}
foo(); // doesn't work
foo(null); // works
foo([]); // works
where instead using
public function foo(array $optionalParam = null);
will accept null, an array, or 0 parameters
<?php
function foo(array $optionalParam = null){
echo "test";
}
foo(null); // works
foo(); // work
foo([]); // works
It's a PHP 7.1 feature called Nullable Types
Both of the lines you wrote are identical.
array ?$optionalParam : either an array or null
array $optionalParam = null : either an array or null
Tho using ? you'd still need to add the parameter when calling the function.
This question already has answers here:
PHP type hinting is being ignored, no TypeError exception is thrown
(1 answer)
What do strict types do in PHP?
(3 answers)
Closed 1 year ago.
I'd have expected the following to generate a type error as 123 is an integer and not a string, so is it okay to provide an integer to a function that expects a string?
foo(123);
function foo(string $str) {
...
}
Yes, because an integer can be converted to string (an array cannot for example).
Yes, unless you declare declare(strict_types=1).
foo(123);
function foo(string $str) {
var_dump($str); // string(3) "123"
}
But the following:
declare(strict_types=1);
function foo(string $str) { }
foo(123); // FAIL (Uncaught TypeError)
Will throw:
Fatal error: Uncaught TypeError: foo(): Argument #1 ($str) must be of type string, int given
The PHP manual is pretty specific about this behavior, and speaks directly to the example you posed:
By default, PHP will coerce values of the wrong type into the expected scalar type declaration if possible. For example, a function that is given an int for a parameter that expects a string will get a variable of type string.
Whether this is "OK" or not (as you asked) is highly implementation-dependent.
This question already has answers here:
Can't use method return value in write context
(8 answers)
Closed 8 years ago.
I have a if statement check to see if a string is empty
if(empty(strlen(trim($_POST['name'])))){
$error_empty = true;
}
gives me this error:
Fatal error: Can't use function return value in write context in C:\xampp\htdocs\requestaccess\index.php on line 51
empty is not a function -- it's a "language construct" that prior to PHP 5.5 can only be used to evaluate variables, not the results of arbitrary expressions.
If you wanted to use empty in exactly this manner (which is meaningless) you would have to store the result in an intermediate variable:
$var = strlen(trim($_POST['name']));
if(empty($var)) ...
But you don't need to do anything like this: strlen will always return an integer, so empty will effectively be reduced to checking for zero. You don't need empty for that; zero converts to boolean false automatically, so a saner option is
if(!strlen(trim($_POST['name']))) ...
or the equivalent
if(trim($_POST['name']) === '') ...
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Immediately executing anonymous functions
I want to immediately evaluate an anonymous function rather than it appearing as a Closure object in method args. Is this possible?
For example:
$obj = MyClass;
$obj->Foo(function(){return "bar";}); // passes a Closure into Foo()
$obj->Foo(function(){return "bar";}()); // passes the string "bar" into Foo()?
The 3rd line is illegal syntax -- is there any way to do this?
Thanks
You could do it with call_user_func ... though that might be a bit silly when you could just assign it to a variable and subsequently invoke the variable.
call_user_func(function(){ echo "bar"; });
You might think that PHP 5.4 with it's dereferencing capabilities would make this possible. You'd be wrong, however (as of RC6, anyway).
This question already has answers here:
PHP Constants Containing Arrays?
(16 answers)
Closed 5 years ago.
Is there a way to define a constant array in PHP?
define('SOMEARRAY', serialize(array(1,2,3)));
$is_in_array = in_array($x, unserialize(SOMEARRAY));
That's the closest to an array constant.
No, it's not possible. From the manual: Constants Syntax
Only scalar data (boolean, integer, float and string) can be contained in constants. It is possible to define constants as a resource, but it should be avoided, as it can cause unexpected results.
If you need to set a defined set of constants, consider creating a class and filling it with class constants. A slightly modified example from the manual:
class MyClass
{
const constant1 = 'constant value';
const constant2 = 'constant value';
const constant3 = 'constant value';
function showConstant1() {
echo self::constant1 . "\n";
}
}
echo MyClass::constant3;
Also check out the link GhostDog posted, it's a nice workaround.
You can not, but you can just define static array in a class and it would serve you just the same, just instead of FOO you'd write Foo::$bar.
don't think you can. But you can always try searching.