note 102865 modified in language.types.array by danbrown

From: Date: Fri, 11 Mar 2011 01:39:11 +0000
Subject: note 102865 modified in language.types.array by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-177783@lists.php.net to get a copy of this message
Sometimes you may need an array of constants including concatenated strings. That works fine in this case: <?php define("GLUE", "&"); function array_to_string($a) { $r = ""; foreach ($a as $key => $value) { $r .= "$key => $value<br>"; }; return $r; } // DECLARING ARRAY (1) $array = array("one", "two", "one".GLUE."two"); echo array_to_string($array); ?> This seems rather strange behavior in a CLASS nevertheless: <?php class wrong_class { // DECLARING ARRAY (2) private $array = array("one", "two", "one".GLUE."two"); function __toString() { return array_to_string($this->array); } } $wc = new wrong_class(); echo $wc; /* Parse error: parse error, expecting `')'' in ... code on line 21 */ ?> Anyway, if you force this declaring method inside a CLASS, you could change the object map directly: <?php class proper_class { function __construct() { // DECLARING ARRAY (3) $this->array = array("one", "two", "one".GLUE."two"); } function __toString() { return array_to_string($this->array); } } $pc = new proper_class(); echo $pc; ?> --was-- // Sometimes you may need an array of constants including concatenated strings. // - That works fine in this case: define("GLUE", "&"); function array_to_string($a) { $r = ""; foreach ($a as $key => $value) { $r .= "$key => $value<br>"; }; return $r; } // DECLARING ARRAY (1) $array = array("one", "two", "one".GLUE."two"); echo array_to_string($array); // - This seems rather strange behavior in a CLASS nevertheless: class wrong_class { // DECLARING ARRAY (2) private $array = array("one", "two", "one".GLUE."two"); function __toString() { return array_to_string($this->array); } } $wc = new wrong_class(); echo $wc; /* Parse error: parse error, expecting `')'' in ... code on line 21 */ // - Anyway, if you force this declaring method inside a CLASS, you could change the object map directly: class proper_class { function __construct() { // DECLARING ARRAY (3) $this->array = array("one", "two", "one".GLUE."two"); } function __toString() { return array_to_string($this->array); } } $pc = new proper_class(); echo $pc; http://php.net/manual/en/language.types.array.php

« previous php.notes (#177783) next »