Couldn't you just use

return $stmt->fetch() ?: null;

to return null instead of false?

On Wed, May 10, 2017 at 9:51 AM, Csonka Titus <titus1...@msn.com> wrote:

> Greetings,
>
> I want to propose a new PDO FETCH MODE.
>
> Whenever I fetch(http://php.net/manual/en/pdostatement.fetch.php) a
> class, it  returns the new instance of the requested class or false in any
> other cases.
>
> However with the new php7.1 return type declaration(https://wiki.php.
> net/rfc/nullable_types) Upon defining a nullable class as return type, I
> need to add extra code at the end of my function if my database don't have
> a row to return.
>
> PDO will return a false, my function will trigger a fatal error.
>
> My proposal is to add a new style of fetch(PDO::FETCH_NULL_IFNODATA),
> returning null if the PDOStatement::fetch has no result.
>
> //this function will trigger a fatal error if the user is not found
> function getUserByName($name): ?UserClass{
>     $pdo = new PDO(dsn, user, pass, driver_options);
>     $sql = "SELECT * FROM user WHERE name = {$pdo->quote($name)}";
>     $stmt = $pdo->query($sql);
>     $stmt->setFetchMode(PDO::FETCH_CLASS,'UserClass');
>
>     return $stmt->fetch();
> }
>
> //this function will return null representing the absent of user
> function getUserByName($name): ?UserClass{
>     $pdo = new PDO(dsn, user, pass, driver_options);
>     $sql = "SELECT * FROM user WHERE name = {$pdo->quote($name)}";
>     $stmt = $pdo->query($sql);
>     $stmt->setFetchMode(PDO::FETCH_CLASS|PDO::FETCH_NULL_
> IFNODATA,'UserClass');
>
>     return $stmt->fetch();
> }
>
> Looking forward to you answer
>
> Best regards
> Miklos Csonka
>

Reply via email to