<?php

/**
 * base object class
 */
class Object
{
  /**
   * object unique id
   * @var string
   */
  private $__objectId = null;

  /**
   * default ctor
   */
  public function __construct(array $params = array())
  {
    $this->__objectId = md5(spl_object_hash($this)+DateTimeEx::now());
    $this->onCtor($params);
  }

  /**
   *
   */
  function __destruct()
  {
    $this->onDtor();
  }

  /**
   * called by default Object ctor
   * @param array $params
   */
  protected function onCtor(array $params = array())
  {
  }

  /**
   * called by default Object dtor
   */
  protected function onDtor()
  {
  }

  /**
   * return the hash for the current object
   * @return string
   */
  public function getHash()
  {
    return $this->__objectId;
  }

  /**
   * @param Object $obj
   * @return boolean
   */
  public function equals($obj)
  {
    if($obj instanceof Object)
      return $obj->getHash() == $this->getHash();
    return false;
  }

  /**
   * @return string
   */
  public function __toString()
  {
    return get_class()."@".$this->getHash();
  }

  /**
   * @return string
   */
  public function toString()
  {
    return $this->toString();
  }
  
  /**
   * serialize the current object to a string
   * @return string
   */
  public function serialize()
  {
    return serialize($this);
  }
  
  /**
   * deserialize a string to an instance of an Object or derived class
   * @param string $data
   * @param boolean $strict default true
   * @return Object
   */
  public static function deserialize($data,$strict=true)
  {
    $class = get_called_class();
    $obj = unserialize($data);
    if($obj === false)
      return null;
    if(!$strict || ($strict && get_class($obj) == $class))
      return $obj;
    return null;
  }
}
