Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
140 views
in Technique[技术] by (71.8m points)

php - Can I return null instead of an object when a class fails to be initiated?

Is it possible to design a class constructor that destroys the object or sets it to null if it fails to initiate. For example in the code below - if a user isn't found in a database then it could be useful to set the object to Null (A)... or is it better to use a class member flag $found (B)?

<?php
class User {
    private $name = "";
    public  $found = true;

    function __construct($username) {
        if (!db_lookup_user($username)) {
            $this = null;           // A. This won't work - but can I return null instead of an object?
            $this->found = false;   // B. The alternative is to set a flag that indicates that the object is valid
        } else {
            $this->name = $username;
        }
    }
}

$myUser = new User("Donald Duck); 
if (is_null($myUser)) { echo "User doesn't exist"; }
   ... or ...
if ($myUser->found == false) { echo "User doesn't exist"; }
question from:https://stackoverflow.com/questions/65918311/can-i-return-null-instead-of-an-object-when-a-class-fails-to-be-initiated

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use a Factory Pattern (https://en.wikipedia.org/wiki/Factory_method_pattern) (or something close to that)

<?php

class UserFactory {
    static function createUser($username) {
        if($username == 'something') {
            return new User();
        } else {
            return null;
        }
    }
}

class User {}

$user1 = UserFactory::createUser('something');
$user2 = UserFactory::createUser('somethingElse');
var_dump($user1,$user2);

output

object(User)#1 (0) {}
NULL

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...