MongoId::__construct
(PECL mongo >= 0.8.0)
MongoId::__construct — Creates a new id
Description
public MongoId::__construct
([ string
$id
= NULL
] )Parameters
-
id
-
A string to use as the id. Must be 24 hexidecimal characters.
Return Values
Returns a new id.
Changelog
Version | Description |
---|---|
1.4.0 | An exception is thrown when passed invalid string |
Examples
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";
?>
The above example will output something similar to:
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);
?>
The above example will output something similar to:
bool(true)
See Also
- MongoId::__toString() - Returns a hexidecimal representation of this id
- MongoId::isvalid() - Check if a value is a valid ObjectId
- PHP Руководство
- Функции по категориям
- Индекс функций
- Справочник функций
- Расширения для работы с базами данных
- Расширения для работы с базами данных отдельных производителей
- MongoDB
- Types
- Функция MongoId::__construct() - Creates a new id
- Функция MongoId::getHostname() - Gets the hostname being used for this machine's ids
- Функция MongoId::getInc() - Gets the incremented value to create this id
- Функция MongoId::getPID() - Gets the process ID
- Функция MongoId::getTimestamp() - Gets the number of seconds since the epoch that this id was created
- Функция MongoId::isValid() - Check if a value is a valid ObjectId
- Функция MongoId::__set_state() - Create a dummy MongoId
- Функция MongoId::__toString() - Returns a hexidecimal representation of this id
Коментарии
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);
}
}
}
?>