I am looking for a function or class that can effectively outline a class:
class MyClass{
/*
* Perhaps include the function comments
* in the function.
*/
function mainFunction(){
//Does Something
}
function functionWithArgs($arg1,$arg2=false){
//Does Something
//The function I want will give e the arguments w/default values
}
}
Is there a function or library in existence that can give me some kind of access to the information about this class, or even the file.
ex.
get_file_outline('fileWithAboveClass.php');
or
get_class_outline('MyClass');
Does anybody know of either, or know a way of easily writing this?
Take a look at the PHP Reflection API
//use the ReflectionClass to find out about MyClass
$classInfo = new ReflectionClass('MyClass');
//then you can find out pretty much anything you want to know...
$methods = $classInfo->getMethods();
var_dump($methods);
//you can even extract your comments, e.g.
$comment=$classInfo->getMethod('mainFunction')->getDocComment();
Note that for the comment extraction to work, they have to be formatted like PHPDoc / Doxygen comments, and begin with an opening /**
There's also a command line option available for inspecting functions and classes.
$ php --rc DateTime
will give you all the details about the DateTime-class, while
$ php --rf in_array
will give you the arguments of the "in_array" function.
If you're using the Terminal when coding it can be quite handy to use instead of looking it up in the PHP Manual all the time ;)
Related
To make it simple, I have noticed that PHP doesn't seem to offer any magic constant for determining what the name that a trait has been changed to in a class. Since this sounds confusing to me in words, I will give an example, as it is rather easy and would expect it to be somewhere in the new PHP 5.5, I don't see a way to doing it. So here it is:
Say we have some class, that uses some trait that conflicts with some function inside the class, example:
class SomeClass {
use \Name\Space\SomeTrait { SomeFunction as private NewFunctionName; }
function SomeFunction() {
$this->NewFunctionName();
}
}
Since, obviously this class has the "SomeFunction" function, and we are aware that inside of SomeTrait we have included, is a function that is matching by name to a function we have inside this class. Now, since the "SomeFunction" came into this class via a trait inside of a \Name\Space, these 2 functions do 2 different things, but happen to use the same name, and inside of either another function or literally our 'SomeFunction', we then use the "SomeFunction" from our trait, by calling it by the "NewFunctionName".
So hopefully I haven't lost anyone here, as here is what my question comes down to in the above scenario. Within the \Name\Space\SomeTrait\SomeFunction(), how could one get the "NewFunctionName" that this trait function was assigned too? One would think to use a magic method, such as __FUNCTION__, or __METHOD__, or even __TRAIT__, except none of these give the expected result, so does anyone know a way to get this information without passing it to the function as a parameter and resulting in a hacky code? Maybe PHP 5.6 needs to add a new Magic Constant __AS__, or adjust the result of __TRAIT__, I dont understand why __TRAIT__ and __FUNCTION_ need to return the same information (or nearly the same information). Any help would be awesome, if it is an unconventional hacky method, Im interested in seeing my options, until I can open up a bug report with php regarding this. (if it is truly a bug)
edit:
My current, least hacky, method seems to be,
debug_backtrace()[0]['function']
and though it works, I feel it is doing a lot to get a simple string, especially if you use the function a lot. :/
This is the solution I ended up using. It's not very good but probably better than using the debug_backtrace function.
Problem example:
Trait ExampleTrait {
protected function doSomethingRecursive() {
// this is a problem because it could be renamed
$this->doSomethingRecursive();
}
}
Solution example:
Trait ExampleTrait {
protected function doSomethingRecursive() {
// this is a problem because it could be renamed
$this->__internal_doSomethingRecursive();
}
private function __internal_doSomethingRecursive() {
// this works because the class would have
// used and renamed the above function
// but this "internal" function *should*
// remain available under it's original name
$this->__internal_doSomethingRecursive();
}
}
Of course it's possible to break this but for most cases it should be fine. You could also include the name of the trait in the internal function name to further prevent conflicts.
Your current solution is going to be the best, with a couple tweaks:
debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS,1)[0]['function']
The DEBUG_BACKTRACE_IGNORE_ARGS and the frame limit of 1 there will make the backtrace shallow, faster, and use less memory.
This was incredibly surprising to see that PHP has no obvious function to do what I'm looking for, so I'll ask here.
How would you go about getting the number of arguments a particular function has outside of the function (just like func_num_args only from outside the function).
The solution can't actually execute the function (that would be defeating the purpose), and I'd like to do it (preferably) without any sort of reflection class.
Possible?
Oh, you can use the ReflectionFunction class, which inherits from ReflectionFunctionAbstract, which defines the getNumberOfParameters function:
$func_reflection = new ReflectionFunction('function_name');
$num_of_params = $func_reflection->getNumberOfParameters();
Note: This will only work on user functions, not class or instance functions.
In PHP, get_included_files() returns an array with the names of included files.
In a similar fashion, is there any way to get an array with the names of called functions with parameters?
In this way, Is any way to get an array with the names of called functions with parameters?
No.
What you can do is a debug_backtrace() which will show all the function calls (with parameters) that lead to the execution of the line you are doing the backtrace from (the "call stack"), but that's different from all functions that were ever called in the script.
What do you want to do? Maybe there's a different approach.
I was searching for something similar and found xdebug's tracing very useful.
Here's an example of how it could look like:
http://devzone.zend.com/1135/tracing-php-applications-with-xdebug/
I was trying to achieve what you want and finally came up with an reasonable solution.
Make a class named Debug and include that above every file you want to debug in. Build yourself a function that prints nicely the information stored in $calls.
class Debug {
private static $calls;
public static function log($message = null)
{
if(!is_array(self::$calls))
self::$calls = array();
$call = debug_backtrace(false);
$call = (isset($call[1]))?$call[1]:$call[0];
$call['message'] = $message;
array_push(self::$calls, $call);
}
}
Call this function everytime you declare a function first line in the functionbody: Debug::log($message(optional) )
Not that I'm aware.
You can however use debug_backtrace to get the currently active function/method hierarchy.
I don't think there's a way to do what you want. Sorry.
The closest I can get is the function_exists() function, which will tell you whether a specific function has been loaded.
What exactly do you want to achieve here? I can't see a use case (outside of a php_info() type screen) that would require a list of available functions.
You will have to install it as an extension, but a profiler like XHProf will give you a breakdown of which functions are called and how long they take, as well as a callgraph.
XHProf or Webgrind/KCachegrind will show you the functions called, but not their parameters.
You could also use get_defined_functions, which gives you a list of all functions defined. But it won't show you which functions have actually been called, and with what parameters.
If you really need to know the parameters, I don't know of any tools other than a custom logger like the one Henze provided in his answer.
I'm looking to create an on-site API reference for my framework and application.
Basically, say I have a class file model.class.php:
class Model extends Object {
... code here ...
// Separates results into pages.
// Returns Paginator object.
final public function paginate($perpage = 10) {
... more code here ...
}
}
and I want to be able to generate a reference that my developers can refer to quickly in order to know which functions are available to be called. They only need to see the comments directly above each function and the declaration line. Something like this (similar to a C++ header file):
// Separates results into pages.
// Returns Paginator object.
final public function paginate($perpage = 10);
I've done some research and this answer looked pretty good (using Reflection classes), however, I'm not sure how I can keep the comments in.
Any ideas?
I want to keep the current comment formatting. Myself and the people who are working on the code hate the verbosity associated with PHPDocumentor. Not to mention a comment-rewrite of the entire project would take years, so I want to preserve just the // comments in plaintext.
Why don't you just run PHPDocumenter on the code?
PHPDoc is identical to JavaDoc, and will retain all the parameters and comments in the docblock above the function.
EDIT: Since you don't want PHPDoc, I think it would probably be easiest to write a RegEx parser to do it, since Reflection won't provide you with any surrounding comments.
PHP code to get the comment:
if(preg_match("#//(.+)$#",$line,$match)>0)
{
echo "Comment is: ".$match[1];
}
this is what phpdoc is for. you comment your code a specific way, following certain rules, and when you're done you run your code through a parser. It outputs exactly what you're looking for.
I am wondering if php methods are ever defined outside of the class body as they are often done in C++. I realise this question is the same as Defining class methods in PHP . But I believe his original question had 'declare' instead of 'define' so all the answers seem a bit inappropriate.
Update:
Probably my idea of define and declare were flawed. But by define outside of the class body, i meant something equivalent to the C++
class CRectangle {
int x, y;
public:
void set_values (int,int);
int area () {return (x*y);}
};
void CRectangle::set_values (int a, int b) {
x = a;
y = b;
}
All the examples of php code have the the code inside the class body like a C++ inlined function. Even if there would be no functional difference between the two in PHP, its just a question of style.
Here is a terrible, ugly, hack that should never be used. But, you asked for it!
class Bar {
function __call($name, $args) {
call_user_func_array(sprintf('%s_%s', get_class($this), $name), array_merge(array($this), $args));
}
}
function Bar_foo($this) {
echo sprintf("Simulating %s::foo\n", get_class($this));
}
$bar = new Bar();
$bar->foo();
What have I done? Anyway, to add new methods, just prefix them with the name of the class and an underscore. The first argument to the function is a reference to $this.
I stumbled upon this question while looking for a way to separate declaration and implementation of class methods. Why? For the sake of code readability. When the declarations are in a separate file, or at the top of the class file, someone looking to use the class does not have to wade through the whole implementation to find out which methods are offered.
I did find something useful though: PHP interface classes. I don't think they are designed for it, but they serve the purpose: an interface class defines all the methods, and then the "real" class implements them. Here's an article about it:
http://www.davegardner.me.uk/blog/2010/11/21/why-you-should-always-use-php-interfaces/
Having the declaration of methods in header files separate from their implementation is, to my knowledge, pretty unique to C/C++. All other languages I know don't have it at all, or only in limited form (such as interfaces in Java and C#)
It's possible, but very, very hacky and not recommended. No reason to do it either.
First of all, in PHP, all class methods must be defined and implemented within the class structure (class x { }). It is in no way like C++ where you have the implementations (*.cpp) separate from the definitions (*.h).
Natively PHP doesn't support features like this, but since PHP5.4 you can dynamically add methods to object. As an example, you can look at this: https://github.com/ptrofimov/jslikeobject
No. You can consider 'declare' and 'define' to be interchangeable in that question.