MongoId::__construct

(PECL mongo >= 0.8.0)

MongoId::__constructCreates a new id

설명

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

인수

id

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

반환값

Returns a new id.

변경점

버전 설명
1.4.0 An exception is thrown when passed invalid string

예제

Example #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";

  
?>

위 예제의 출력 예시:

49a7011a05c677b9a916612a
49a702d5450046d3d515d10d

Example #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);
  
?>

위 예제의 출력 예시:

bool(true)

참고

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