[php 5.1] class string : nouvel exemple sur la spl

Contenu du snippet

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 / Exemple :


<?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; } ?>

A voir également

Vous n'êtes pas encore membre ?

inscrivez-vous, c'est gratuit et ça prend moins d'une minute !

Les membres obtiennent plus de réponses que les utilisateurs anonymes.

Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.

Le fait d'être membre vous permet d'avoir des options supplémentaires.