回应财产的名称,而不是价值?

时间:2016-01-25 22:18:53

标签: php wordpress class oop

我需要访问我动态的$ his->键的名称,而不是它的值。见下面的例子:

<?php

    class foo {

        public $bar;

        public function __construct() {
            $this->bar = 'I am the value.';
            $this->echobar();
        }

        public function echobar() {
            echo $this->bar;
        }
    }

    $foo = new foo();

?>

我基本上想要回复 bar ,而不是我是价值。但是如何?

1 个答案:

答案 0 :(得分:1)

我认为@Barmar是对的,但你仍然可以这样做: -

<?php
    class foo {
        public $bar;
        public function __construct() {
            $this->bar = 'I am the value.';
            $this->echobar();
        }
        public function echobar() {
            echo $this->bar;
        }
    }
    $foo = new foo();
    echo "<pre/>";print_r(array_keys(get_object_vars ($foo))[0]);//get the properties and there values in array key->value pair(through get_object_vars()) format and then get the keys only (properties name) and then print the first one.
?>

输出: - https://eval.in/507775