What does question mark (?) before type declaration means in php (?int)
It's called Nullable types
.
Which defines ?int
as either int
or null
.
Type declarations for parameters and return values can now be marked as nullable by prefixing the type name with a question mark. This signifies that as well as the specified type, NULL can be passed as an argument, or returned as a value, respectively.
Example :
function nullOrInt(?int $arg){
var_dump($arg);
}
nullOrInt(100);
nullOrInt(null);
function nullOrInt
will accept both null and int.
Ref: http://php.net/manual/en/migration71.new-features.php
What is the purpose of the question marks before type declaration in PHP7 (?string or ?int)?
What is a Nullable Type?
Introduced in PHP 7.1,
Type declarations for parameters and return values can now be marked as nullable by prefixing the type name with a question mark. This signifies that as well as the specified type, NULL can be passed as an argument, or returned as a value, respectively.
In parameters
function test(?string $parameter1, string $parameter2) {
var_dump($parameter1, $parameter2);
}
test("foo", "bar");
test(null, "foo");
test("foo", null); // Uncaught TypeError: Argument 2 passed to test() must be of the type string, null given,
With variadic arguments
In this example, you can pass null
or string
parameters :
function acceptOnlyStrings(string ...$parameters) { }
function acceptStringsAndNull(?string ...$parameters) { }
acceptOnlyStrings('foo', null, 'baz'); // Uncaught TypeError: Argument #2 must be of type string, null given
acceptStringsAndNull('foo', null, 'baz'); // OK
Return type
The return type of a function can also be a nullable type, and allows to return null
or the specified type.
function error_func(): int {
return null ; // Uncaught TypeError: Return value must be of the type integer
}
function valid_func(): ?int {
return null ; // OK
}
function valid_int_func(): ?int {
return 2 ; // OK
}
Property type (as of PHP 7.4)
The type of a property can be a nullable type.
class Foo
{
private object $foo = null; // ERROR : cannot be null
private ?object $bar = null; // OK : can be null (nullable type)
private object $baz; // OK : uninitialized value
}
See also :
Nullable union types (as of PHP 8.0)
As of PHP 8, "?T
notation is considered a shorthand for the common case of T|null
"
class Foo
{
private ?object $bar = null; // as of PHP 7.1+
private object|null $baz = null; // as of PHP 8.0
}
Error
In case of the running PHP version is lower than PHP 7.1, a syntax error is thrown:
syntax error, unexpected '?', expecting variable (T_VARIABLE)
The ?
operator should be removed.
PHP 7.1+
function foo(?int $value) { }
PHP 7.0 or lower
/**
* @var int|null
*/
function foo($value) { }
References
As of PHP 7.1: Nullable type :
As of PHP 7.4: Class properties type declarations.
As of PHP 8.0: Nullable Union Type
What do the question marks mean in a PHP function signature?
The question mark represents a nullable type:
Type declarations for parameters and return values can now be marked as nullable by prefixing the type name with a question mark. This signifies that as well as the specified type, NULL can be passed as an argument, or returned as a value, respectively.
This allows you to provision null
as an argument without receiving a TypeError
.
Method followed by colon and a question mark and a class
This syntax means that the method is forced to return NULL
(what the question mark stands for) or and instance of the declared class. Refer to: php docs.
If something else is returned, this will cause an error like: Return value of Name\Space::method() must be of the type ..., ... returned in /Path/To/File.php on line ...
.
It's good practice to use this strict typing in object oriented programming so the code is more unambiguous and less sensitive to errors.
But it's not obligated to use, your code will work perfectly fine if you remove the return type and just use public function getParentProject()
.
PHP functions attached with : and ? , what does it do?
This is known as a nullable type, and is introduced in PHP 7.1:
Type declarations for parameters and return values can now be marked as nullable by prefixing the type name with a question mark. This signifies that as well as the specified type,
NULL
can be passed as an argument, or returned as a value, respectively.
Essentially, the function can return either the specified type or null
. If it would return a different type, an error is thrown:
function answer(): ?int {
return null; // ok
}
function answer(): ?int {
return 42; // ok
}
function answer(): ?int {
return new stdclass(); // error
}
What does :? after a method means in PHP?
This is a new feature as of PHP 7.1. See the explanation here
Type declarations for parameters and return values can now be marked as nullable by prefixing the type name with a question mark. This signifies that as well as the specified type, NULL can be passed as an argument, or returned as a value, respectively.
This means the expected output of your function will be either an Instance of the class Article
or it is NULL
.
What's the purpose of PHP7's returning values type declaration
If you're writing a library for other code to consume, it's good to have a well-defined API, and declared return types are part of that. It saves people having to ferret around in the source code to work it out.
For your own code usage, it's a safety check that you're writing your function correctly, and staying "on plan". It encourages your functions to do one thing, and to stay focused. PHP itself is a bit of a mess in places where it has functions which might return an integer value or a boolean if something didn't go according to plan. This is pretty terrible coding. It means the calling code has to code for both eventualities, which it shouldn't need to do. If you specify a return type on your function, you'll not be able to go down that route.
Also as others have said, it helps your IDE to work out what's supposed to be going on as well. That's handy. IDEs will also leverage those phpdoc annotation comments, but they're comments so they lie, and don't actually enforce a contract, so aren't really... a good thing.
PHP nullable type declaration
There is no difference as string is nullable by default.
Btw, this was introduced in PHP 7.1: https://www.php.net/manual/en/migration71.new-features.php
Related Topics
Why Is MySQLi Giving a "Commands Out of Sync" Error
PHP Error: Fatal Error: Constant Expression Contains Invalid Operations
How to Stop People Hacking the PHP-Based Highscore Table of a Flash Game
List of All Locales and Their Short Codes
Remove New Lines from String and Replace With One Empty Space
Convert Flat Array to a Delimited String to Be Saved in the Database
Simultaneous Requests to PHP Script
PHP Reading Shell_Exec Live Output
Simple PHP Post-redirect-get Code Example
How to Increase the Execution Timeout in PHP
Storing Files in Database VS File System
PHP Associative Array Duplicate Keys
How to Minify PHP Page HTML Output
Split String by New Line Characters
Create Word Document Using PHP in Linux
Correctly Determine If Date String Is a Valid Date in That Format