|
Trouver une ressource
Vous ne trouvez pas de réponse à votre problème ? Alors posez la question dans le forum. Souvenez-vous qu'il n'y a jamais de question bête, mais rester dans l'ignorance parce que l'on n'ose pas poser une question, ça c'est une erreur !
[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
SURCHARGE PHP, ARRAYLIST PHP, ARRAYMAP PHP, DEBOGAGE, DBMANAGER, DESSIN PHP, ETC... (PHP 5)Implémentation de :
- Surcharge de méthodes (grâce à un simple héritage)
- Arraylist et Arraymap avec Itérateur (+ une interface list et map pour ... SURCHARGE PHP, ARRAYLIST PHP, ARRAYMAP PHP, DEBOGAGE, DBMANA...
par DijxDreaM
Sources en rapport avec celle ci
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
|
Téléchargements
Logiciels à télécharger sur le même thème :
|