简体   繁体   中英

How to get vars of method php

I want to create Auto breadcrumb as array contain sub arrays with 2 keys ( 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 .

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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