国外的PHP程序员面试题目一解
题目三: Create a class, Test3, with the following behavior:
The class must take a string of the format
name1=value1:name2=value2:name3=value3 consisting of name and value
pairs, separated by the : symbol. I must be able to enter as many
pairs as I like when I call the class, the only limit is that each
pair is formated as name=value and multiple pairs are separated by
the : symbol.
When an object of the class is created it must end up with a variable
for each name=value pair. The name of the variable must be the same
as the name part of the substring and the value of the variable must
be the same as the value part of the substring. For example: creating an object with new Test3("firstname=david:lastname=smith")
must create variables within the class:
$firstname = "david";
$lastname = "smith"; and new Test3("food1=pasta:food2=chocolate") must create variables
within the class:
$food1 = "pasta";
$food2 = "chocolate"; I should be able to use any variable names and values provided they
do not include the symbols : or = You should then write a function print_all that will print the all
the names of the defined variables in the class along with their
values in the following format:
Variable 1 – Name = (whatever the actual name is), Value = (whatever
the actual value is)
Variable 2 – Name = (whatever the actual name is), Value = (whatever
the actual value is)
Variable 3 – Name = (whatever the actual name is), Value = (whatever
the actual value is)
and so on until all the variables are listed. The last line of output of the print_all function should be the words
"The original input was " followed by a string that is an exact
representation of the string parameter supplied when creating the
class object. For example, if you did new Test3("firstname=david:lastname=smith")
then the print_all function should output: Variable 1 – Name = firstname, Value = david
Variable 2 – Name = lastname, Value = smith
The original imput was ("firstname=david:lastname=smith") This must work for any input string that has the correct format and
you may not store the complete input string or directly output it to
produce the last line of the print_all function output as that would
be too easy.
PHP代码
- class Test3 {
- private $keys = array();
- function __construct($args) {
- $this->Test3($args);
- }
- function Test3($args) {
- $arr = explode(":", $args);
- foreach($arr as $v) {
- $varr = explode("=", $v);
- $key = $varr[0];
- $value = $varr[1];
- $this->$key = $value;
- array_push($this->keys, $key);
- }
- }
- function print_all() {
- $ret = array();
- foreach($this->keys as $key) {
- array_push($ret, $key."=".$this->$key);
- }
- return implode(":", $ret);
- }
- }
- $t = new Test3("name=seaprince:name2=renothing");
- print_r($t);
- print $t->print_all();
- ?> </li> </ol> </div>