【问题标题】:Echo a property's name, not value?回显属性的名称,而不是值?
【发布时间】:2016-01-25 22:18:53
【问题描述】:

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

<?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,而不是我是价值。但是如何?

【问题讨论】:

  • get_object_vars ( object $object )
  • 只要echo "bar"
  • 我怀疑这个问题比你所展示的要多,但我不确定它是什么。

标签: php wordpress class oop


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-23
    • 2020-04-28
    相关资源
    最近更新 更多