Accueil > > > [PHP 5.1] CLASS STRING : NOUVEL EXEMPLE SUR LA SPL
[PHP 5.1] CLASS STRING : NOUVEL EXEMPLE SUR LA SPL
Information sur la source
Description
Cette classe a été écrite essentiellement pour montrer que l'on peut très facilement écrire ne classe pratique et amusante grâce à la SPL (http://www.php.net/~helly/php/ext/spl/main.html). Elle permet d'utiliser les fonctions de tableaux, ou les méthodes de la classe ArrayIterator sur une chaîne.
Source
- <?php
- /**
- * Basic error handler to convert php errors into php exceptions. Best use a more complete one...
- *
- * @param int $errno
- * @param string $errstr
- * @param string $errfile
- * @param int $errline
- */
- function ErrorToException($errno, $errstr, $errfile, $errline) {
- throw new Exception($errstr, $errno);
- }
-
- /**
- * Setting our error handler
- */
- set_error_handler('ErrorToException');
-
- /**
- * class string
- * @author : Johan Barbier <barbier_johan@hotmail.com>
- * @version : 20080513
- * @desc : small string class which allows to use strings as arrays. This class was mainly written to show how the SPL coult be used easily to make funny stuff!
- *
- */
- class string implements Iterator, Countable, SeekableIterator {
- /**
- * Parameter in which the string will be stored, as an ArrayIterator object
- *
- * @var ArrayIterator
- */
- private $aChaine;
-
- /**
- * Constants defined to se the return by reference or not trick in the string::__call() method
- *
- */
- const RETURNS_REFERENCE_USED = true;
- const RETURNS_REFERENCE_NOT_USED = false;
-
- /**
- * Constructor. Needs a string as first and only parameter
- *
- * @param string $sChaine
- */
- public function __construct($sChaine) {
- if(!is_string($sChaine)) {
- throw new InvalidArgumentException('Parameter must be a string');
- }
- $this->aChaine = new ArrayIterator(str_split($sChaine));
- }
-
- /**
- * Here is the magic : __call will allow to call any methods of the ArrayIterator class, or any function...these should be array functions, or there might be an error
- *
- * @param string $sFunction : function/method to be called
- * @param array $aArgs : array of arguments for the function/method to be called.
- * @return mixed
- */
- public function __call($sFunction, $aArgs) {
- /**
- * Case we call an ArrayIterator method
- */
- if(method_exists($this->aChaine, $sFunction)) {
- return call_user_func_array(array($this->aChaine, $sFunction), $aArgs);
- /**
- * Case we try to call a basic function
- */
- } elseif(function_exists($sFunction)) {
- /**
- * Try to find the firs array parameter of the function asked for, so that we could replace it with our ArrayIterator
- * IF the first argument is a boolean, it is used as the $bReturnsByReference variable; it means that IF the function called returns an array, then our string object will be replaced by this return. The exemple shows how it works with the array_reverse() function.
- */
- if(!isset($aArgs[0]) || !is_bool($aArgs[0])) {
- $bReturnsByReference = string::RETURNS_REFERENCE_NOT_USED;
- } else {
- $bReturnsByReference = $aArgs[0];
- array_shift($aArgs);
- }
- $oFuncRef = new reflectionFunction($sFunction);
- $iKeepPos = null;
- foreach($oFuncRef->getParameters() as $iPos => $oParamRef) {
- if($oParamRef->isArray()) {
- $iKeepPos = $iPos;
- break;
- }
- }
- if(!is_null($iKeepPos)) {
- $aKeepArgs = $aArgs;
- $iCpt = 0;
- foreach($aKeepArgs as $iK => $mVal) {
- if($iK === $iKeepPos) {
- $aArgs[$iCpt] = $this->aChaine->getArrayCopy();
- ++$iCpt;
- } else {
- $aArgs[$iCpt] = $mVal;
- }
- ++$iCpt;
- }
- } else {
- /**
- * If we could not find any array in the arguments of the function (ParameterReflection::isArray() does not work very well with old functions...too bad...) we force it assuming that the array is the first argument. If not...well, there will be an error!
- */
- array_unshift($aArgs, $this->aChaine->getArrayCopy());
- }
- $mReturn = call_user_func_array($sFunction, $aArgs);
- if(is_array($mReturn) && string::RETURNS_REFERENCE_USED === $bReturnsByReference) {
- $this->aChaine = new ArrayIterator($mReturn);
- }
- return $mReturn;
- }
- throw new BadMethodCallException($sFunction.' does not exist');
- }
-
- /**
- * Returns the string
- *
- * @return string
- */
- public function __toString() {
- $s = '';
- $this->rewind();
- while($this->valid()) {
- $s .= $this->current();
- $this->next();
- }
- $this->rewind();
- return $s;
- }
-
- public function valid() {
- return $this->aChaine->valid();
- }
-
- public function current() {
- return $this->aChaine->current();
- }
-
- public function next() {
- $this->aChaine->next();
- }
-
- public function key() {
- return $this->aChaine->key();
- }
-
- public function rewind() {
- $this->aChaine->rewind();
- }
-
- public function count() {
- return $this->aChaine->count();
- }
-
- public function seek($offset) {
- $this->aChaine->seek($offset);
- }
- }
-
- try {
- /**
- * Instanciation
- */
- $sChaine = 'Hello World!!';
- $oChaine = new string($sChaine);
-
- /**
- * basic loop on each character of our string
- */
- foreach($oChaine as $iK => $sV) {
- echo $iK, ' => ', $sV, "\n";
- }
-
- /**
- * Use natcasesort() on our string...!
- * Here, we do not need to use the $bReturnsByReference boolean flag because the natcasesort() used here is NOT the function, but the ArrayIterator method.
- */
- $oChaine->natcasesort();
- echo $oChaine, "\n";
-
- /*
- * Reverse our string...!
- * We give the function a parameter, a boolean true, because we want the return of array_reverse() to be used as our new string object.
- */
- $oChaine->array_reverse(string::RETURNS_REFERENCE_USED);
- echo $oChaine, "\n";
- /**
- * Count occurences of each unique character in our string. As this function returns an array, we explicitely ask that this array won't be used to replace our current string object (if we had not told anything, it would not have done so anyway)
- */
- print_r($oChaine->array_count_values(string::RETURNS_REFERENCE_NOT_USED));
- echo $oChaine, "\n";
-
- /**
- * Here, we deliberately call an invalid function, it will be caught by the basic error handler
- */
- echo $oChaine->floor(2);
-
- } catch(Exception $e) {
- echo $e;
- }
- ?>
<?php
/**
* Basic error handler to convert php errors into php exceptions. Best use a more complete one...
*
* @param int $errno
* @param string $errstr
* @param string $errfile
* @param int $errline
*/
function ErrorToException($errno, $errstr, $errfile, $errline) {
throw new Exception($errstr, $errno);
}
/**
* Setting our error handler
*/
set_error_handler('ErrorToException');
/**
* class string
* @author : Johan Barbier <barbier_johan@hotmail.com>
* @version : 20080513
* @desc : small string class which allows to use strings as arrays. This class was mainly written to show how the SPL coult be used easily to make funny stuff!
*
*/
class string implements Iterator, Countable, SeekableIterator {
/**
* Parameter in which the string will be stored, as an ArrayIterator object
*
* @var ArrayIterator
*/
private $aChaine;
/**
* Constants defined to se the return by reference or not trick in the string::__call() method
*
*/
const RETURNS_REFERENCE_USED = true;
const RETURNS_REFERENCE_NOT_USED = false;
/**
* Constructor. Needs a string as first and only parameter
*
* @param string $sChaine
*/
public function __construct($sChaine) {
if(!is_string($sChaine)) {
throw new InvalidArgumentException('Parameter must be a string');
}
$this->aChaine = new ArrayIterator(str_split($sChaine));
}
/**
* Here is the magic : __call will allow to call any methods of the ArrayIterator class, or any function...these should be array functions, or there might be an error
*
* @param string $sFunction : function/method to be called
* @param array $aArgs : array of arguments for the function/method to be called.
* @return mixed
*/
public function __call($sFunction, $aArgs) {
/**
* Case we call an ArrayIterator method
*/
if(method_exists($this->aChaine, $sFunction)) {
return call_user_func_array(array($this->aChaine, $sFunction), $aArgs);
/**
* Case we try to call a basic function
*/
} elseif(function_exists($sFunction)) {
/**
* Try to find the firs array parameter of the function asked for, so that we could replace it with our ArrayIterator
* IF the first argument is a boolean, it is used as the $bReturnsByReference variable; it means that IF the function called returns an array, then our string object will be replaced by this return. The exemple shows how it works with the array_reverse() function.
*/
if(!isset($aArgs[0]) || !is_bool($aArgs[0])) {
$bReturnsByReference = string::RETURNS_REFERENCE_NOT_USED;
} else {
$bReturnsByReference = $aArgs[0];
array_shift($aArgs);
}
$oFuncRef = new reflectionFunction($sFunction);
$iKeepPos = null;
foreach($oFuncRef->getParameters() as $iPos => $oParamRef) {
if($oParamRef->isArray()) {
$iKeepPos = $iPos;
break;
}
}
if(!is_null($iKeepPos)) {
$aKeepArgs = $aArgs;
$iCpt = 0;
foreach($aKeepArgs as $iK => $mVal) {
if($iK === $iKeepPos) {
$aArgs[$iCpt] = $this->aChaine->getArrayCopy();
++$iCpt;
} else {
$aArgs[$iCpt] = $mVal;
}
++$iCpt;
}
} else {
/**
* If we could not find any array in the arguments of the function (ParameterReflection::isArray() does not work very well with old functions...too bad...) we force it assuming that the array is the first argument. If not...well, there will be an error!
*/
array_unshift($aArgs, $this->aChaine->getArrayCopy());
}
$mReturn = call_user_func_array($sFunction, $aArgs);
if(is_array($mReturn) && string::RETURNS_REFERENCE_USED === $bReturnsByReference) {
$this->aChaine = new ArrayIterator($mReturn);
}
return $mReturn;
}
throw new BadMethodCallException($sFunction.' does not exist');
}
/**
* Returns the string
*
* @return string
*/
public function __toString() {
$s = '';
$this->rewind();
while($this->valid()) {
$s .= $this->current();
$this->next();
}
$this->rewind();
return $s;
}
public function valid() {
return $this->aChaine->valid();
}
public function current() {
return $this->aChaine->current();
}
public function next() {
$this->aChaine->next();
}
public function key() {
return $this->aChaine->key();
}
public function rewind() {
$this->aChaine->rewind();
}
public function count() {
return $this->aChaine->count();
}
public function seek($offset) {
$this->aChaine->seek($offset);
}
}
try {
/**
* Instanciation
*/
$sChaine = 'Hello World!!';
$oChaine = new string($sChaine);
/**
* basic loop on each character of our string
*/
foreach($oChaine as $iK => $sV) {
echo $iK, ' => ', $sV, "\n";
}
/**
* Use natcasesort() on our string...!
* Here, we do not need to use the $bReturnsByReference boolean flag because the natcasesort() used here is NOT the function, but the ArrayIterator method.
*/
$oChaine->natcasesort();
echo $oChaine, "\n";
/*
* Reverse our string...!
* We give the function a parameter, a boolean true, because we want the return of array_reverse() to be used as our new string object.
*/
$oChaine->array_reverse(string::RETURNS_REFERENCE_USED);
echo $oChaine, "\n";
/**
* Count occurences of each unique character in our string. As this function returns an array, we explicitely ask that this array won't be used to replace our current string object (if we had not told anything, it would not have done so anyway)
*/
print_r($oChaine->array_count_values(string::RETURNS_REFERENCE_NOT_USED));
echo $oChaine, "\n";
/**
* Here, we deliberately call an invalid function, it will be caught by the basic error handler
*/
echo $oChaine->floor(2);
} catch(Exception $e) {
echo $e;
}
?>
Historique
- 13 mai 2008 18:40:07 :
- Petit oubli dans les commentaires
- 14 mai 2008 14:14:45 :
- quelques modifs pour pouvoir mieux contrôler le retour des fonctions
Sources du même auteur
Sources de la même categorie
Commentaires et avis
Discussions en rapport avec ce code source dans le forum
Couleur des objets d'une page web [ par Farfadet ]
Bon alors, c'est maintenant connu que la couleur des barres de défilements peuvent changer. Mais il est possible de changer le style d'autres objets.
recherche dans une chaine de caractere [ par lalles ]
Salutdans une chaîne de caractère, j'essai d'extraire un morceau de chaîne de caractère comprise entre deux chaînes de caractères de référence.ex:la c
Demandesr les fichiers et les tableaux [ par TheLenain ]
Voila je n'arrive pas a faire un script me permettant de mettre des données ASCII dans un tableau de facon dynamique.Mes fichiers sont de se genre : D
Quelle alternative aux FRAMES ? [ par BSide ]
Bonjour,on m'a récemment reproché d'utiliser des frames dans mon intranet en me disant qu'il était mieux (?) de n'utiliser que des tableaux qui étaien
probleme avec une requete [ par tripoutch ]
Je débute dans le PHP et les bases de données.J'ai un gros probleme avec une requete.Voici grosso modo le script : <?$connexion = mysql_connect("lo
récuperer des infos sur un site web [ par nunor ]
Bonjour,Je débute en PHP.Je souhaiterais savoir s'il est possible de récupérer dans une base de données différentes informations. Ces informations son
récuperer des infos sur un site web [ par nunor ]
Bonjour,Je débute en PHP.Je souhaiterais savoir s'il est possible de récupérer dans une base de données différentes informations. Ces informations son
extraire chaîne caractères [ par eax ]
salutj'ai un petit pb de traitement de chaines de caractères :j'ai une variable avec du contenu dedans (je ne sais pas ce qu'il y a exactement dedans
probleme avec un tableaux (ou est l'erreur??) [ par h2h ]
salut tout le monde, jai un probleme avec ce tableaux.. en fait ce tableaux affiche bien ce ke je veu mai le prob cest kil décale tout d'une ligne ce
Chois entre plusieurs tableaux (4, 6, 8 cellules) [ par Brikse ]
Hello à tous, Alors, je voudrais savoir si quelqu'un a une idée pour choisir tel ou tel tableau (4, 6 ou 8 cellules) dans la partie Admin d'un site po
|
Derniers Blogs
GESTION D'EXCEPTION AVEC LES TASKSGESTION D'EXCEPTION AVEC LES TASKS par richardc
Nous avons vu dans un précédent article comment utiliser Task pour effectuer des opérations dans un autre thread.
Malheureusement, comme tout le monde n'est pas parfait, il se peut que cette exécution se passe mal et qu'une exception se produise.
La...
Cliquez pour lire la suite de l'article par richardc DéMARRONS AVEC LES TASKSDéMARRONS AVEC LES TASKS par richardc
Que vous le vouliez ou non, le développement multi-tâche est maintenant une obligation pour toute nouvelle application. Il est donc vital d'en comprendre les mécanismes et de s'y mettre le plus tôt possible.
En attendant le .NET Framework 4.5 avec le...
Cliquez pour lire la suite de l'article par richardc SLIDE & DéMO TECHDAYS 2012 - FAST & FURIOUS XAML APPSSLIDE & DéMO TECHDAYS 2012 - FAST & FURIOUS XAML APPS par Vko
Retrouvez les slides et les démo de ma session Fast & Furious XAML Apps. A ceux qui se posent la question : "est-ce que le code de la DataGrid est disponible?", je vous répondrais "pas encore". Je vais mettre en place un projet codeplex pour part...
Cliquez pour lire la suite de l'article par Vko XNA IS DEAD!XNA IS DEAD! par richardc
Depuis la semaine dernière (et grâce aux TechDays 2012), je me penche activement sur la nouvelle version de Windows, aka Windows 8. Vous me direz, il était temps puisque la première preview date de Septembre dernier.
OK. Remarquez, on n'en est qu'aux...
Cliquez pour lire la suite de l'article par richardc TECHDAYS PARIS 2012 : WINDOWS SERVER "8" QUOI DE 9 !TECHDAYS PARIS 2012 : WINDOWS SERVER "8" QUOI DE 9 ! par ROMELARD Fabrice
Speakers: Fabrice Meillon et Stanislas Quastana Cette session est basée entièrement sur celle donnée lors de la BUILD cet hiver. Il n'y a pas d'ajout d'information en rapport avec cet évènement passé. Windows 8 Server sera intégralem...
Cliquez pour lire la suite de l'article par ROMELARD Fabrice
Forum
SYSTEME D'AMISYSTEME D'AMI par moza2409
Cliquez pour lire la suite par moza2409
Logiciels
DocTranslate (V3.1.0.0)DOCTRANSLATE (V3.1.0.0)DocTranslate est un traducteur de document Microsoft Word, PowerPoint et Excel. Il permet d'autom... Cliquez pour télécharger DocTranslate Tribler (2012)TRIBLER (2012)Tribler est un client pair à pair (P2P/Peer-to-Peer) open source avec la capacité de regarder des... Cliquez pour télécharger Tribler OneSwarm (2012)ONESWARM (2012)Le peer-to-peer qui protège votre vie privée, c'est OneSwarm.
Ce logiciel de peer-to-peer crypté... Cliquez pour télécharger OneSwarm PONAMEDIA PREMIUM - HELLLOOO FLASH DEMO (V8.4)PONAMEDIA PREMIUM - HELLLOOO FLASH DEMO (V8.4)PONAMEDIA TV DEVIENS HELLLOOO FLASH
LA TV SUR VOTRE ORDINATEUR.
Toute une plateforme Multi... Cliquez pour télécharger PONAMEDIA PREMIUM - HELLLOOO FLASH DEMO Academy System (17.2.1.0)ACADEMY SYSTEM (17.2.1.0)Logiciel de gestion des établissements.
- élèves/étudiants (inscription, dossier, absence...)
-... Cliquez pour télécharger Academy System
|