IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Langage PHP Discussion :

[Tableaux] var_dump amélioré depuis developpez.com


Sujet :

Langage PHP

  1. #1
    Membre éprouvé

    Profil pro
    Inscrit en
    Octobre 2003
    Messages
    1 163
    Détails du profil
    Informations personnelles :
    Âge : 39
    Localisation : France

    Informations forums :
    Inscription : Octobre 2003
    Messages : 1 163
    Points : 1 148
    Points
    1 148
    Par défaut [Tableaux] var_dump amélioré depuis developpez.com
    Bonjour à tous,

    je me suis récement mis au PHP donc ne m'en veuillez pas si je fais d'éventuelles fautes de débutants.

    J'ai trouvé un var_dump amélioré dans la page des sources PHP de développez.com.

    Afin de l'intégrer dans ma classe Debug (un ensemble de méthodes statiques essentiellement) et de la rendre récursive je l'ai un peu modifié....au point que ça ne sort plus rien du tout.

    Si je "débug" avec des "echo" je me rend compte que c'est la fonction get_object_vars qui me retourne un tableau vide alors qu'un vrai var_dump m'affiche bien un début de description de l'objet (un début car ça se termine par ...).

    Si dessous le code :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    		/** Var_dump personnalisé tiré de www.developpez.com
    		 * @param obj Objet ou tableau à afficher
    		 * @param prefix Affiche le préfixe ou pas (??????)
    		 * @param stack [rec] Pile de stockage
    		 * @param depth [rec] Profondeur actuelle
    		 * @return Ancienmment $str
    		 */
    	static public function dumpFormat( $obj, $prefix = false, 
    											   &$stack = array(),
    											   &$depth = 0 )
    	{  		
    		$str = '';
    		$struct = array();
     
    //		--- Format de dump ----------------------------------------------------
       		$format = array (
      			 '&nbsp;&nbsp;&nbsp;&nbsp;<b><span style="color:#66B">%1$s</span>
       			  </b> => <i><span style="color:#6B6">(%2$s)</span></i> %3$s<br />', // Variable simple
       			'<div style="border-left:3px solid #66B;margin-left:20px;margin-top:10px"><b>
       			<span style="color:#66B;background-color:#DDD">&nbsp;%1$s&nbsp;</span>
       			</b> => <b>{</b> <span style="color:#6B6">(%2$s)</span><br />', // Début de container
       			'&nbsp;<b>}</b><span style="color:#66B">(%1$s)</span></div>', // Fin de container
       			'', // Indentation
       			'key' // repère de balisage
    		);
     
     //		--- On fait le dump ---------------------------------------------------
     
     		if ( is_null( $obj ) )
     		{
     			$str .= str_repeat( $format[3], $depth ).sprintf($format[0], '[NULL]', 'NULL', 'NULL', $depth );
     		}
     
       		if ( is_object( $obj ) )
       		{
    	   		$struct = get_object_vars( $obj );
       		} else { /* Continuer */ }
     
     		if ( is_scalar( $struct ) )
          	{
            	$str .= str_repeat( $format[3], $depth ).
             		sprintf( $format[0], '[unknown]', gettype( $struct ), $struct, $depth );
          	} else
          	{
          		var_dump( $struct );
          		foreach ( $struct as $key => $val )
       			{
          			if ( $prefix )
          			{
             			if ( preg_match( '(^\d)', $key ) )
             			{
             				$key = $prefix.$key;
             			} else { /* Ne rien faire */ }
    	      		} else { /* Ne rien faire */ }
     
        	  		$type = gettype( $val );
     
          			if ( is_object( $val ) )
          			{
            			array_push( $stack, ${$format[4]} );
             			$str .= str_repeat( $format[3], $depth ).
             				sprintf( $format[1], $key, $type, $val, $depth );
             			$depth++;
             			$str .= Debug::dumpFormat( get_object_vars($val), $prefix, $stack, $depth );
          			} elseif ( is_array( $val ) )
          			{
             			array_push( $stack, ${$format[4]} );
             			$str .= str_repeat( $format[3], $depth ).
             				sprintf( $format[1], $key, $type, $val, $depth );
             			$depth++;
             			$str .= Debug::dumpFormat( $val, $prefix, $stack, $depth );
          			} elseif ( is_scalar( $val ) )
          			{
             			$str .= str_repeat( $format[3], $depth ).
    	         			sprintf( $format[0], $key, $type, $val, $depth );
        	  		}
       			}
          	}
     
     
       		$depth--;
       		if ( $depth != -1 )
       		{
          		${$format[4]} = array_pop( $stack );
          		return ($str .= str_repeat( $format[3], $depth ).
          			sprintf( $format[2], $key, $type, $val, $depth ));
       		} else
       		{    		
          		return $str;
       		}
    	}
    En espérant que vous pourrez m'aider,

    Merci d'avance.

    Ah oui j'oubliais quelque chose qui à peut être son importance :
    Mon serveur est un Apache2 sous une ubuntu-server.
    La version de php utilisée est : 5.1.16

  2. #2
    Membre confirmé Avatar de goodpz
    Profil pro
    Inscrit en
    Février 2007
    Messages
    475
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Février 2007
    Messages : 475
    Points : 514
    Points
    514
    Par défaut
    Heureusement que le code est très lisible
    Je ne connais pas la source du 'var_dump amélioré', alors j'ai uniquement modifié des trucs par rapport à ton code:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    class Debug {
      /** Var_dump personnalisé tiré de www.developpez.com
      * @param obj Objet ou tableau à afficher
      * @param prefix Affiche le préfixe ou pas (??????)
      * @param stack [rec] Pile de stockage
      * @param depth [rec] Profondeur actuelle
      * @return Ancienmment $str
      */
     
       // virrer la référence sur le $depth;
      static public function dumpFormat( $obj, $prefix = false, &$stack = array(), $depth = 0 ) {  		
        $str = '';
        $struct = array();
     
        //		--- Format de dump ----------------------------------------------------
        $format = array (
          '&nbsp;&nbsp;&nbsp;&nbsp;<b><span style="color:#66B">%1$s</span></b> 
            => <i><span style="color:#6B6">(%2$s)</span></i> %3$s<br />', // Variable simple
          '<div style="border-left:3px solid #66B;margin-left:20px;margin-top:10px"><b>
          <span style="color:#66B;background-color:#DDD">&nbsp;%1$s&nbsp;</span></b>
            => <b>{</b> <span style="color:#6B6">(%2$s)</span><br />', // Début de container
          '&nbsp;<b>}</b><span style="color:#66B">(%1$s)</span></div>', // Fin de container
          '', // Indentation
          'key' // repère de balisage
        );
     
        //		--- On fait le dump ---------------------------------------------------
     
        if ( is_null( $obj ) ) {
          $str .= str_repeat( $format[3], $depth ).sprintf($format[0], '[NULL]', 'NULL', 'NULL', $depth );
        }
     
        if ( is_object( $obj ) ) {
          $struct = get_object_vars( $obj );
        }
        else {
          $struct = $obj;  ///// AJOUT
        }
     
        if ( is_scalar( $struct ) ) {
          $str .= str_repeat( $format[3], $depth ).sprintf( $format[0], '[unknown]', gettype( $struct ), $struct, $depth );
        }
        else {
          //var_dump( $struct );
          foreach ( $struct as $key => $val ) {
            if ( $prefix ) {
              if ( preg_match( '/^\d/', $key ) ) {
                $key = $prefix.$key;
              }
              else { /* Ne rien faire */ }
            }
            else { /* Ne rien faire */ }
     
            $type = gettype( $val );
     
            if ( is_object( $val ) ) {
              array_push( $stack, ${$format[4]} );
              $str .= str_repeat( $format[3], $depth ).sprintf( $format[1], $key, $type, $val, $depth );
              $str .= Debug::dumpFormat( get_object_vars($val), $prefix, $stack, $depth + 1); // AJOUT +1
            }
            elseif ( is_array( $val ) ) {
              array_push( $stack, ${$format[4]} );
              $str .= str_repeat( $format[3], $depth ).sprintf( $format[1], $key, $type, $val, $depth);
              $str .= Debug::dumpFormat( $val, $prefix, $stack, $depth + 1);  // AJOUT +1
            }
            elseif ( is_scalar( $val ) ) {
              $str .= str_repeat( $format[3], $depth ).sprintf( $format[0], $key, $type, $val, $depth );
            }
          }
        }
     
        $depth--;
        if ( $depth != -1 ) {
          ${$format[4]} = array_pop( $stack );
          return ($str .= str_repeat( $format[3], $depth ).sprintf( $format[2], $key, $type, $val, $depth ));
        }
        else {    		
          return $str;
        }
      }
    }  
     
     
    $a = new StdClass;
    $a->dd = 'AA';
     
    $b = new StdClass;
    $b->da = $a;
    $b->ar = array("str", 33);
     
    $c = new StdClass;
    $c->cc = $b;
     
    echo Debug::dumpFormat($c);
    Est-ce que c'est ce que tu attends ?

  3. #3
    Membre éprouvé

    Profil pro
    Inscrit en
    Octobre 2003
    Messages
    1 163
    Détails du profil
    Informations personnelles :
    Âge : 39
    Localisation : France

    Informations forums :
    Inscription : Octobre 2003
    Messages : 1 163
    Points : 1 148
    Points
    1 148
    Par défaut
    Effectivement cela fonctione avec ton exemple. Mais lorsque je l'utilise sur mes classes à moi cela n'a aucun effet :S

    As tu une explication à cela ?
    Peut tu m'expliquer tes modifications ?

    Merci par avance !

  4. #4
    Membre confirmé Avatar de goodpz
    Profil pro
    Inscrit en
    Février 2007
    Messages
    475
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Février 2007
    Messages : 475
    Points : 514
    Points
    514
    Par défaut
    Ok. Nouveau fix: Rajoute ça dans le if ($depth != -1) :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    if (!isset($type))  {
      $val = $obj;
      $type = gettype($val);
    }
    Sinon, j'ai rajouté en commentaires (sommaires!) les modifs que j'ai effectuées.
    (j'avais également modifié le preg_match sans le noter)

    Edit: on ne peut pas récupérer les membres protected ou private avec cette méthode

  5. #5
    Membre éprouvé

    Profil pro
    Inscrit en
    Octobre 2003
    Messages
    1 163
    Détails du profil
    Informations personnelles :
    Âge : 39
    Localisation : France

    Informations forums :
    Inscription : Octobre 2003
    Messages : 1 163
    Points : 1 148
    Points
    1 148
    Par défaut
    Ok mais ça ne change pas le résultat si j'applique la méthode à une de mes classes perso.

    Faut il qu'elles héritent d'une classe particulière pour que cela fonctionne (get_object_vars retournant un tableau vide....) ?

  6. #6
    Membre confirmé Avatar de goodpz
    Profil pro
    Inscrit en
    Février 2007
    Messages
    475
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Février 2007
    Messages : 475
    Points : 514
    Points
    514
    Par défaut
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    class testa {
      public $pro = array('pro3','proo3');
    }
    class testb {
      public $pub = 'pub';
      public $pri = 'prb';
    }
    class testc extends testb {
      public $pub2 = 33;
      function __construct() { $this->obj = new testa; }
     
    }
    $c = new testc;
    echo Debug::dumpFormat($c, "PRE");
    Ceci fonctionne... Je ne sais pas trop quel est ton problème. Tente peut être de nous montrer la structure de certaines de tes classes

    Edit: j'avais édité mon précédent post mais ça n'a pas du être pris en compte (le site avait des probs).
    Donc j'avais ajouté: ceci ne fonctionne qu'avec des membres public. Les autres sont ignorés par get_obj_vars

Discussions similaires

  1. Ou trouver la liste de mes messages postés depuis Developpez.com ?
    Par Newbie49 dans le forum Mode d'emploi & aide aux nouveaux
    Réponses: 2
    Dernier message: 08/08/2009, 01h10
  2. Réponses: 30
    Dernier message: 05/08/2009, 19h25

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo