简体   繁体   English

如何获取方法php的变量

[英]How to get vars of method php

I want to create Auto breadcrumb as array contain sub arrays with 2 keys ( link, title ). 我想创建自动面包屑,因为数组包含具有2个键(link,title)的子数组。 like this: 像这样:

array (
    0 => array (
        'link' => 'index',
        'title' => 'Home :)',
    ),
    1 => array (
        'link' => 'advanced',
        'title' =>  'Advanced Setting :)'
    )
);

Note 注意

when i use the following code it give me this result but i cannot get the title as you can see on the variable $mytitle . 当我使用以下代码时,它给了我这个结果,但是我无法获得标题,正如您在变量$mytitle上看到的那样。

class Setting extends Controller {
    public function __construct() {
        $relflection = new ReflectionClass ( get_class ( $this ) );
        $methods = $relflection->getMethods ( ReflectionMethod::IS_PUBLIC );
        if (is_array ( $methods )) {
            foreach ( $methods as $method ) {
                if ($method->class == get_class ( $this )) {
                    $breadcrumb[] = array("link" => $method->name, "title" => "???");
                }
            }
        }
        $breadcrumb = $breadcrumb;
    }

    public function index() {
        $mytitle = "Home :)";
    }

    public function advanced() {
        $mytitle = "Advanced Setting :)";
    }
}

Can anyone here give me a right solution for this? 这里有人可以给我一个正确的解决方案吗?

I hope I'm not wildly far from your need, but this could work: 我希望我离您的需求不远,但这可以起作用:

first assign your breadcrumb to an actual property, or it won't be accessible out of your constructor's scope: 首先将面包屑分配给实际属性,否则将无法在构造函数的范围内访问它:

$this->breadcrumb = $breadcrumb;

then from this question you can devise a way to get your function name: 然后从这个问题,您可以设计一种获取函数名称的方法:

function getMyCallerName() {
  $array = debug_backtrace();
  return $array[1]['function'];
} 
// since you call a function to have your function name, the right caller will be the second function in the backtrace

you need a function to get the desired title from your breadcrumbs: 您需要一个函数来从面包屑中获取所需的标题:

function getTitleFromLink($link) {
  foreach ($this->breadcrumb as $array) {
  if ($array['link'] == $link) return $array['title'];
  }
}

then you can use it in your index() function: 然后可以在index()函数中使用它:

public function index() {
  $title = getTitleFromLink(getMyCallerName()); // should be "Home :)"
}
public function advanced() {
  $title = getTitleFromLink(getMyCallerName()); // should be "Advanced Setting :)"
}

you can then add any logic you wish in your index function 然后可以在索引函数中添加任何所需的逻辑

be sure to put those function in your class or getTitleFromLink() will not be able to use the breadcrumb property 确保将这些函数放在您的类中,否则getTitleFromLink()将无法使用breadcrumb属性

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM