Accueil > > > POO - OBJECT CLASS
POO - OBJECT CLASS
Information sur la source
Description
Une classe "racine" permettant d'éviter des erreurs fatales et facilitant le débogue, il suffit de l'étendre pour profiter de ces fonctionnalités.
Source
- <?php
- /**
- * Class Object is the root of the class hierarchy.
- *
- * Every class has Object as a superclass and implements following features:
- * - Adds the ability to reverse-engineer classes, interfaces, functions,
- * methods and extensions of the object using PHP reflection API;
- * - Generates an unique identifier of an object that can be used as a hash key
- * for storing objects or for identifying an object;
- * - Prints a representation of the object when it is converted to a string;
- * - Avoids fatal errors (throws LogicException or BadMethodCallException
- * instead) when:
- * - writing or reading data from inaccessible properties;
- * - calling isset(), empty() or unset() on inaccessible properties;
- * - calling an object as a function;
- * - calling inaccessible methods in an object or static context.
- *
- * @author Quentin Berlemont <quentinberlemont@gmail.com>
- * @copyright Copyright (C) 2010 Quentin Berlemont
- * @license http://www.gnu.org/licenses/lgpl.html LGPLv3
- */
- abstract class Object
- {
- /**
- * Returns an instance of ReflectionObject.
- *
- * The ReflectionObject class is a part of the PHP Reflection API that adds
- * the ability to reverse-engineer classes, interfaces, functions, methods
- * and extensions of an object.
- *
- * See the {@link http://php.net/reflection Reflection API} feature for more
- * information.
- *
- * @param void
- * @return ReflectionObject Returns an instance of ReflectionObject.
- */
- final public function getReflection()
- {
- static $reflection = null;
-
- return $reflection ?: $reflection = new ReflectionObject($this);
- }
-
- /**
- * Returns an unique identifier of the object.
- *
- * This identifier is unique for each object and is always the same for the
- * same object. It can be used as a key for storing objects or for
- * identifying an object.
- *
- * See the {@link http://php.net/spl-object-hash spl_object_hash} feature
- * for more information.
- *
- * @param void
- * @return string Returns an unique identifier of the object.
- */
- final public function getHashCode()
- {
- return spl_object_hash($this);
- }
-
- /**
- * Prints a representation of the object when it is converted to a string.
- *
- * The string consisting of the name of the class of which the object is an
- * instance, the at-sign character `@`, and the unique identifier for the
- * object.
- *
- * @param void
- * @return string Returns a string representation of the object.
- */
- public function __toString()
- {
- return $this->getReflection()->getName() . '@' . $this->getHashCode();
- }
-
- /**
- * Throws an LogicException when writing data to inaccessible properties.
- *
- * @param string $propertyName The name of the property being set.
- * @param mixed $propertyValue The value for the property.
- * @return void
- * @throws LogicException If one tries to write data to inaccessible
- * properties.
- */
- public function __set($propertyName, $propertyValue)
- {
- $className = $this->getReflection()->getName();
-
- throw new LogicException("Write data to inaccessible property `{$className}::{$propertyName}`.");
- }
-
- /**
- * Throws an LogicException when reading data from inaccessible properties.
- *
- * @param string $propertyName The name of the property to retrieve.
- * @return void
- * @throws LogicException If one tries to read data from inaccessible
- * properties.
- */
- public function __get($propertyName)
- {
- $className = $this->getReflection()->getName();
-
- throw new LogicException("Read data from inaccessible property `{$className}::{$propertyName}`.");
- }
-
- /**
- * Throws an LogicException when calling isset() or empty() on inaccessible
- * properties.
- *
- * @param string $propertyName The name of the property to be checked.
- * @return void
- * @throws LogicException If one tries to apply isset() or empty() on
- * inaccessible property.
- */
- public function __isset($propertyName)
- {
- $className = $this->getReflection()->getName();
-
- throw new LogicException("Apply isset() or empty() on inaccessible property `{$className}::{$propertyName}`.");
- }
-
- /**
- * Throws an LogicException when calling unset() on inaccessible properties.
- *
- * @param string $propertyName The name of the property to be unset.
- * @return void
- * @throws LogicException If one tries to apply unset() on inaccessible
- * property.
- */
- public function __unset($propertyName)
- {
- $className = $this->getReflection()->getName();
-
- throw new LogicException("Apply unset() on inaccessible property `{$className}::{$propertyName}`.");
- }
-
- /**
- * Avoids a fatal error when calling an object as a function, throwing a
- * LogicException instead.
- *
- * @param void
- * @return void
- * @throws LogicException If one tries to call an object as a function.
- */
- public function __invoke()
- {
- $className = $this->getReflection()->getName();
-
- throw new LogicException("Call object `{$className}` as a function.");
- }
-
- /**
- * Avoids a fatal error when calling inaccessible methods in an object
- * context, throwing a BadMethodCallException instead.
- *
- * @param string $methodName The name of the method being called.
- * @param array $arguments Optional, an enumerated array containing the
- * arguments passed to the method.
- * @return void
- * @throws BadMethodCallException If one tries to call inaccessible methods
- * in an object context.
- */
- public function __call($methodName, array $arguments = null)
- {
- $className = $this->getReflection()->getName();
-
- throw new BadMethodCallException("Call to inaccessible method `{$className}::{$methodName}()`.");
- }
-
- /**
- * Avoids a fatal error when calling inaccessible methods in a static
- * context, throwing a BadMethodCallException instead.
- *
- * @param string $methodName The name of the method being called.
- * @param array $arguments Optional, an enumerated array containing the
- * arguments passed to the method.
- * @return void
- * @throws BadMethodCallException If one tries to call inaccessible methods
- * in a static context.
- */
- static public function __callStatic($methodName, array $arguments = null)
- {
- $className = get_called_class();
-
- throw new BadMethodCallException("Call to inaccessible static method `{$className}::{$methodName}()`.");
- }
- }
-
- // Example
-
- class Foo extends Object
- {
- const CONST_VALUE = 'A constant value';
-
- private $_var = null;
-
- public function bar()
- {
- echo 'Hello World !';
- }
- }
-
- try {
- $foo = new Foo();
-
- // pritns: Array ( [CONST_VALUE] => A constant value )
- // print_r($foo->getReflection()->getConstants());
-
- // prints: 0000000050ce9726000000002e61f3e9
- // echo $foo->getHashCode();
-
- // prints: Foo@0000000050ce9726000000002e61f3e9
- // echo $foo;
-
- // prints (LogicException): Write data to inaccessible property `Foo::_var`.
- // $foo->_var = 'Some value';
-
- // prints (LogicException): Call object `Foo` as a function.
- // $foo('Hello World !');
-
- // prints (BadMethodCallException): Call to inaccessible method `Foo::method().
- // $foo->method();
-
- // prints (BadMethodCallException): Call to inaccessible static method
- // `Foo::method()`.
- // $foo::method();
-
- // prints: Hello World !
- // $foo->bar();
- }
- catch (Exception $exception) {
- echo $exception->getMessage() . PHP_EOL;
- }
- ?>
<?php
/**
* Class Object is the root of the class hierarchy.
*
* Every class has Object as a superclass and implements following features:
* - Adds the ability to reverse-engineer classes, interfaces, functions,
* methods and extensions of the object using PHP reflection API;
* - Generates an unique identifier of an object that can be used as a hash key
* for storing objects or for identifying an object;
* - Prints a representation of the object when it is converted to a string;
* - Avoids fatal errors (throws LogicException or BadMethodCallException
* instead) when:
* - writing or reading data from inaccessible properties;
* - calling isset(), empty() or unset() on inaccessible properties;
* - calling an object as a function;
* - calling inaccessible methods in an object or static context.
*
* @author Quentin Berlemont <quentinberlemont@gmail.com>
* @copyright Copyright (C) 2010 Quentin Berlemont
* @license http://www.gnu.org/licenses/lgpl.html LGPLv3
*/
abstract class Object
{
/**
* Returns an instance of ReflectionObject.
*
* The ReflectionObject class is a part of the PHP Reflection API that adds
* the ability to reverse-engineer classes, interfaces, functions, methods
* and extensions of an object.
*
* See the {@link http://php.net/reflection Reflection API} feature for more
* information.
*
* @param void
* @return ReflectionObject Returns an instance of ReflectionObject.
*/
final public function getReflection()
{
static $reflection = null;
return $reflection ?: $reflection = new ReflectionObject($this);
}
/**
* Returns an unique identifier of the object.
*
* This identifier is unique for each object and is always the same for the
* same object. It can be used as a key for storing objects or for
* identifying an object.
*
* See the {@link http://php.net/spl-object-hash spl_object_hash} feature
* for more information.
*
* @param void
* @return string Returns an unique identifier of the object.
*/
final public function getHashCode()
{
return spl_object_hash($this);
}
/**
* Prints a representation of the object when it is converted to a string.
*
* The string consisting of the name of the class of which the object is an
* instance, the at-sign character `@`, and the unique identifier for the
* object.
*
* @param void
* @return string Returns a string representation of the object.
*/
public function __toString()
{
return $this->getReflection()->getName() . '@' . $this->getHashCode();
}
/**
* Throws an LogicException when writing data to inaccessible properties.
*
* @param string $propertyName The name of the property being set.
* @param mixed $propertyValue The value for the property.
* @return void
* @throws LogicException If one tries to write data to inaccessible
* properties.
*/
public function __set($propertyName, $propertyValue)
{
$className = $this->getReflection()->getName();
throw new LogicException("Write data to inaccessible property `{$className}::{$propertyName}`.");
}
/**
* Throws an LogicException when reading data from inaccessible properties.
*
* @param string $propertyName The name of the property to retrieve.
* @return void
* @throws LogicException If one tries to read data from inaccessible
* properties.
*/
public function __get($propertyName)
{
$className = $this->getReflection()->getName();
throw new LogicException("Read data from inaccessible property `{$className}::{$propertyName}`.");
}
/**
* Throws an LogicException when calling isset() or empty() on inaccessible
* properties.
*
* @param string $propertyName The name of the property to be checked.
* @return void
* @throws LogicException If one tries to apply isset() or empty() on
* inaccessible property.
*/
public function __isset($propertyName)
{
$className = $this->getReflection()->getName();
throw new LogicException("Apply isset() or empty() on inaccessible property `{$className}::{$propertyName}`.");
}
/**
* Throws an LogicException when calling unset() on inaccessible properties.
*
* @param string $propertyName The name of the property to be unset.
* @return void
* @throws LogicException If one tries to apply unset() on inaccessible
* property.
*/
public function __unset($propertyName)
{
$className = $this->getReflection()->getName();
throw new LogicException("Apply unset() on inaccessible property `{$className}::{$propertyName}`.");
}
/**
* Avoids a fatal error when calling an object as a function, throwing a
* LogicException instead.
*
* @param void
* @return void
* @throws LogicException If one tries to call an object as a function.
*/
public function __invoke()
{
$className = $this->getReflection()->getName();
throw new LogicException("Call object `{$className}` as a function.");
}
/**
* Avoids a fatal error when calling inaccessible methods in an object
* context, throwing a BadMethodCallException instead.
*
* @param string $methodName The name of the method being called.
* @param array $arguments Optional, an enumerated array containing the
* arguments passed to the method.
* @return void
* @throws BadMethodCallException If one tries to call inaccessible methods
* in an object context.
*/
public function __call($methodName, array $arguments = null)
{
$className = $this->getReflection()->getName();
throw new BadMethodCallException("Call to inaccessible method `{$className}::{$methodName}()`.");
}
/**
* Avoids a fatal error when calling inaccessible methods in a static
* context, throwing a BadMethodCallException instead.
*
* @param string $methodName The name of the method being called.
* @param array $arguments Optional, an enumerated array containing the
* arguments passed to the method.
* @return void
* @throws BadMethodCallException If one tries to call inaccessible methods
* in a static context.
*/
static public function __callStatic($methodName, array $arguments = null)
{
$className = get_called_class();
throw new BadMethodCallException("Call to inaccessible static method `{$className}::{$methodName}()`.");
}
}
// Example
class Foo extends Object
{
const CONST_VALUE = 'A constant value';
private $_var = null;
public function bar()
{
echo 'Hello World !';
}
}
try {
$foo = new Foo();
// pritns: Array ( [CONST_VALUE] => A constant value )
// print_r($foo->getReflection()->getConstants());
// prints: 0000000050ce9726000000002e61f3e9
// echo $foo->getHashCode();
// prints: Foo@0000000050ce9726000000002e61f3e9
// echo $foo;
// prints (LogicException): Write data to inaccessible property `Foo::_var`.
// $foo->_var = 'Some value';
// prints (LogicException): Call object `Foo` as a function.
// $foo('Hello World !');
// prints (BadMethodCallException): Call to inaccessible method `Foo::method().
// $foo->method();
// prints (BadMethodCallException): Call to inaccessible static method
// `Foo::method()`.
// $foo::method();
// prints: Hello World !
// $foo->bar();
}
catch (Exception $exception) {
echo $exception->getMessage() . PHP_EOL;
}
?>
Historique
- 13 janvier 2010 10:44:20 :
- Correction mineures.
Sources du même auteur
Sources de la même categorie
Commentaires et avis
Discussions en rapport avec ce code source dans le forum
[POO] Une classe dans une classe [ par Mrreivax ]
Bonsoir.Et bien voila. J'ai créé une classe de gestion des images.J'ai par la suité créé une autre classe de gestion de banières.Mais, cette dernière
templates avec poo [ par lesnes ]
bonjours je reprogramme totalement mon site en poo et je souhaiterai utiliser les templates mais l'on ne peut pas faire appel a une class exterieur a
Class POO retourné le nom de l'objet [ par MeTh ]
Bonjour,Comment retourné le nom de l'objet déclaré?exemple :$monobjet = new GridR();comment recuperé $monobjet dans ma class?Merci
Include, class et array [ par Hades5k ]
Bonjour! J'ai un petit problème à utiliser un array dans un fichier que j'inclus... voici un peu le code : <?php $classNames = array(); include_onc
Problem d'affichage de resultat de requete sous forme de tableau [ par jbcaiz ]
explication : je fais un requete de recherche dans ma base, qui doit normalement me sortir plusieur résultat.je veux que ces résultat s'affiche dans u
OBJECT EMBED + BLOB [ par RealKEV1 ]
Bonjour,Je récupére grace à php un objet .wmv crypté type LongBlob ( stocké dans une table mysql). Et je voudrais faire une page html spéciale pour po
OBJECT EMBED + BLOB WMA [ par RealKEV1 ]
Bonjour,Je récupére grace à php un objet .wma crypté type LongBlob (stocké dans ma table mysql). Et je voudrais faire une page html spéciale pour pouv
Serveur SMTP [ par Marion0904 ]
Bonsoir, J'essai d'nvoyer des mails en utilisant la class phpmailer (disponible sur http://phpmailer.sourceforge.net/). J'incu la class php mail
AU SECOURS ! (je suis prêt à me jeter par la fenêtre) [ par nougitch ]
Bonjour, Je possède un tableau. J'aimerai que quand je clique sur une donnée elle se colore. Quand quand je reclique dessus, elle retrouve
class,PDF,XLS et boucles..... [ par booth ]
bonjour!j'ai un méga problème...je dois générer un PDF et une grillle excel toutes deux issues d'un moteur de recherche...pour le moteur de recherche
|
Derniers Blogs
IMAGINE CUP 2012, MAKE A SIGN EN FINALEIMAGINE CUP 2012, MAKE A SIGN EN FINALE par junarnoalg
Voilà qui est fait, la nouvelle est officielle ! L'équipe belge "Make a Sign" va au pays des kangourous défendre son projet dans la catégorie Software Design. http://www.imaginecup.com/CompetitionsContent/Competition/WorldwideFinalists.aspx V...
Cliquez pour lire la suite de l'article par junarnoalg KINECT 1.5 IS OUT !KINECT 1.5 IS OUT ! par Vko
La version 1.5 du Kinect For Microsoft vient tout juste de sortir ! Plein de nouveautés: Tracking de squelette en Near Mode Détection en position assise Détection faciale avec un SDK dédié Documentation et des guideline (enfin) Un out...
Cliquez pour lire la suite de l'article par Vko LES ACTUALITéS DE LA SEMAINE SUR C2I.FR (14 MAI - 20 MAI) LES ACTUALITéS DE LA SEMAINE SUR C2I.FR (14 MAI - 20 MAI) par richardc
Mise à jour des Web API du 14 Mai
Réservez dès maintenant votre journée du 20 juin pour le Windows Azure Dev Camp 2012 à Paris
Mise à jour de Team Foundation Service
MechCommander 2 sur Windows 8
Entity Framework 5 Release Candidate e...
Cliquez pour lire la suite de l'article par richardc REACTIVE EXTENSIONS : CONSOMMER DES SERVICES AVEC RX PARTIE 3, LES PIèGES à éVITERREACTIVE EXTENSIONS : CONSOMMER DES SERVICES AVEC RX PARTIE 3, LES PIèGES à éVITER par Groc
Une mauvaise utilisation de rx lors de l'écriture d'une couche d'accès à des services peut conduire à des cas embarassants avec des erreurs mal gérées, des appels qui ne partent lorsqu'ils le devraient, et même des résultats incorrects . le tout nuis...
Cliquez pour lire la suite de l'article par Groc SHAREPOINT BLOG SITE, PROBLèME D'ARCHIVESSHAREPOINT BLOG SITE, PROBLèME D'ARCHIVES par junarnoalg
Dernièrement, nous avons migré le site
myTIC
vers un nouveau serveur SharePoint 2010. Dans les contenus que nous vouloins récupérer, nous avions un certain nombre de blogs.
Nous avons utilisé les commandes Power...
Cliquez pour lire la suite de l'article par junarnoalg
Logiciels
sDEVIS-FACTURES vlPRO (8.1.0.3)SDEVIS-FACTURES VLPRO (8.1.0.3)sDEVIS-FACTURES vlPRO a été mis au point pour les particuliers, créateurs, entrepreneurs, artisa... Cliquez pour télécharger sDEVIS-FACTURES vlPRO 974 Application Server (12.2.4.6)974 APPLICATION SERVER (12.2.4.6)Développez de puissantes applications dans un environnement de 'cloud computing', clusterisé, séc... Cliquez pour télécharger 974 Application Server vPicture (1.4.2.1)VPICTURE (1.4.2.1)Avec vPicture, hébergez vos images facilement et rapidement.
vPicture est un utilitaire simple, ... Cliquez pour télécharger vPicture Easy-Planning (2.2.1.6)EASY-PLANNING (2.2.1.6)Easy-Planning permet de créer des plannings sous la représentation de diagrammes et est adapté au... Cliquez pour télécharger Easy-Planning COM-BACKUP (2.0)COM-BACKUP (2.0)
COM-BACKUP est un logiciel de sauvegarde qui permet de planifier les sauvegardes de vos dossiers ...
Cliquez pour télécharger COM-BACKUP
|