1

I have this class

class MyClass{
    private $id;
    private $name;
    public function __construct ($id, $name){
        $this->name = $name;
    }
}

$ob1 = new MyClass(1, 'earth');
$ob2 = new MyClass(2, 'sky');
$ob3 = new MyClass(3, 'ocean');

I want that my objects $ob1, $ob2 and $ob3 have a different attribute $id. For example when i make this :

$ob4 = new MyClass(3, 'wood');

The code denies me to create the object

Thanks

1
  • No there is no database. it is just variables in memory. Commented Jan 16, 2016 at 20:21

1 Answer 1

3

You need to keep track of the ids in a static class property:

class MyClass {
    static private $ids = [];

    public function __construct($id) {
        if (in_array($id, self::$ids)) {
            throw new Exception("Object with id $id already constructed");
        }
        self::$ids[] = $id;
    }
}

Having said this, I would question the usefulness of this. It just sounds like a recipe for problems. You should keep track of unique data as part of some business logic and database interaction, probably not as something enforced on a language level.

Sign up to request clarification or add additional context in comments.

1 Comment

Can be handy as a repository. You could even add a static function getInstance($id) that returns an object with that id from the static array, or constructs a new one if it doesn't exist yet. But whether this is really the best implementation for it.. Mwah..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.