0

如果在类中调用方法,我需要能够从我的一个类中的私有属性中回显一个值。解释起来有点棘手,所以让我演示一下,希望有人可以为我填空:)

     <?php
     class test {
          private $array['teachers']['classes'][23] = "John";


             public function __construct($required_array) {

                 $this->array['teachers']['classes'][23] = "John";
                 $this->array['students'][444] = "Mary";
                 $this->echo_array($required_array);

             }
             public function echo_array($array) {

                     // Echo the value from the private $this->array;
                     // remembering that the array I pass can have either 
                     // 1 - 1000 possible array values which needs to be 
                     // appended to the search. 

             }
     }

     // Getting the teacher:     
     $test = new test(array('teachers','classes',23));

     // Getting the student:     
     $test = new test(array('students',444));

?>

这可能吗?

4

2 回答 2

3
$tmp = $this->array;
foreach ($array as $key) {
    $tmp = $tmp[$key];
}
// $tmp === 'John'
return $tmp; // never echo values but only return them
于 2013-01-20T19:58:40.730 回答
0

另一种获得价值的方法;

class Foo {
    private $error = false,
            $stack = array(
        'teachers' => array(
            'classes' => array(
                23 => 'John',
                24 => 'Jack',
            )
        )
    );

    public function getValue() {
        $query  = func_get_args();
        $stack  = $this->stack;
        $result = null;
        foreach ($query as $i) {
            if (!isset($stack[$i])) {
                $result = null;
                break;
            }
            $stack  = $stack[$i];
            $result = $stack;
        }

        if (null !== $result) {
            return $result;
        }
        // Optional
        // trigger_error("$teacher -> $class -> $number not found `test` class", E_USER_NOTICE);
        // or
        $this->error = true;
    }

    public function isError() {
        return $this->error;
    }
}

$foo = new Foo();
$val = $foo->getValue('teachers', 'classes', 24); // Jack
// $val = $foo->getValue('teachers', 'classes'); // array: John, Jack
// $val = $foo->getValue('teachers', 'classes', 25); // error
if (!$foo->isError()) {
    print_r($val);
} else {
    print 'Value not found!';
}
于 2013-01-20T20:35:08.697 回答