MongoId::__construct

(PECL mongo >= 0.8.0)

MongoId::__constructCreates a new id

Beschreibung

public MongoId::__construct ([ string|MongoId $id = NULL ] )

Parameter-Liste

id

A string (must be 24 hexadecimal characters) or a MongoId instance.

Rückgabewerte

Returns a new id.

Changelog

Version Beschreibung
1.4.0 An exception is thrown when passed invalid string

Beispiele

Beispiel #1 MongoId::__construct() example

This example shows how to create a new id. This is seldom necessary, as the driver adds an id to arrays automatically before storing them in the database.

<?php

  $id1 
= new MongoId();
  echo 
"$id1\n";

  
$id2 = new MongoId();
  echo 
"$id2\n";

  
?>

Das oben gezeigte Beispiel erzeugt eine ähnliche Ausgabe wie:

49a7011a05c677b9a916612a
49a702d5450046d3d515d10d

Beispiel #2 Parameter example

This example shows how to use a string parameter to initialize a MongoId with a given value.

<?php
  $id1 
= new MongoId();

  
// create a new id from $id1
  
$id2 = new MongoId("$id1");

  
// show that $id1 and $id2 have the same hexidecimal value
  
var_dump($id1 == $id2);
  
?>

Das oben gezeigte Beispiel erzeugt eine ähnliche Ausgabe wie:

bool(true)

Siehe auch

add a note add a note

User Contributed Notes 1 note

up
7
georgedot nospam gmail guess what com
11 years ago
Due to Recent changes.

* [PHP-554] - MongoId should not get constructed when passing in an invalid ID.

Constructor will throw an exception when passing invalid ID.

<?php

$_id
= new MongoId(); //Generates new ID
$_id = new MongoId(null); //Generates new ID

$_id = new MongoId("invalid id"); //throws MongoException

?>

<?php
//Revert to old behaviour
$_id = "invalid id";
try {
   
$_id = new MongoId($_id);
} catch (
MongoException $ex) {
   
$_id = new MongoId();
}
?>

<?php
//Nifty hack
class SafeMongoId extends MongoId {

    public function
__construct($id=null) {

        try {
           
parent::__construct($id);
        } catch (
MongoException $ex) {
           
parent::__construct(null);
        }

    }
}
?>
To Top