How to find places where a non-static method is called? - php

In the case of the following example,
I can not easily find the places where get() of Book class is called by searching files with get.
Because there are a lot of get which do not belong to Book class.
class Book {
function get() {
}
}
class Pen {
function get() {
}
}
$obj = new Pen;
$obj->get();
$obj = new Book;
$obj->get();
But if I use just functions or static methods like the following codes,
I can easily find the places by searching files with Book_get or Book::get.
And if I use functions, I can find both where the function is called and where the function is defined by searching only with Book_get.
function Book_get() {
}
function Pen_get() {
}
Book_get();
Pen_get();
class Book {
static function get() {
}
}
class Pen {
static function get() {
}
}
Book::get();
Pen::get();
When I use non-static methods, how can I easily find the places where they are called?
Or is it better to use functions or static methods instead of non-static methods as possible?

You can always temporarily rename get to something like xget and rebuild to find the calling points.

When I use non-static methods, how can I easily find the places where they are called?
A class member function can be called in a number of ways,
Through instance of class
Through polymorphic behavior(dynamic dispatch)
For first case, any reasonably good code analysis tool or IDE will be able to tell you the class from which the function is being called depending on type of the object, but
I guess there is no easy way to track the second case without examining the code, I doubt any of the code analysis tools are intelligent enough to tell you exactly which class method is being called(Source Insight surely doesn't) because the dispatch is dynamic not compile time.
Is it better to use functions or static methods instead of non-static methods as possible?
To use or not use a static method needs much deeper thought than just to be able to find functions in a search.
Static functions do not have this pointer so you cannot access non static members inside it.They can only operate on static members of the class.

Switching to a better IDE is the simplest solution. Eclipse CDT for example allows you to view the caller hierarchy and find all call sites of a method. (Although, advanced cases of templates and inheritance might still make it hard to figure)

If your method needs access to data in this->, then you have to make it a non-static method. Then the object needs to be instantiated (via new).
If all your method uses is data contained in function parameters, then consider making your method static. Or create a separate class with static methods only.
Book::get();
Pen::get(); this will be the best to use in nonstatic

Related

PHP: Calling a function whenever a function in a child class is called

Within a single class, I am able to use the _call/_callStatic functions to call a function before any function is actually run. However, I'm yet to find a solution that I can apply to the parent, and it will be inherited by the children.
The only method I can think of is putting a small snippet of code within each class that calls a function in the parent, which contains my code.
Are there any better solutions that I can implement?
As long as you are at least on php 5.4, you could use traits.
http://php.net/traits
This will need some adjustments in your code but could allow the desired behavior.
Do you have some more information on your use case? I think of logging from your description, is this correct?
Unfortunately there are not magic methods in PHP which get run whenever any method is called.
I think the solution you are looking for is a decorator, see this article for the tips on decorating methods / classes in PHP.
how to implement a decorator in PHP?
It's hard to help you without seeing some code. However, assuming that you don't re-define __call/__callStatic in the subclass, it should simply inherit the method from it's superclass.
If you do re-define __call/__callStatic in the subclass, it overrides the superclass' definition. So you'd somehow have to call the superclass' method. In order to do this you can use the parent keyword. See this example:
class SuperClass
{
public function __call($name, $arguments)
{
// Do some stuff
}
}
class SubClass extends SuperClass
{
public function __call($name, $arguments)
{
// Execute the parent's __call() method
return parent::__call($name, $arguments);
// Do some extra stuff here
}
}

Difference in Class Calling PHP

With learning fuelPHP, I am introduced on calling classes using scope resolution, or :: in sense. Typically, when we call a method in a class we do this ...
$myclass = new myclass();
$myclass->mymethod();
On fuel, methods are usually called in this manner ...
myclass::mymethod();
I was wondering if there are any difference between the two? Is the scope resolution is something of an update on 5.3 as well ... if not, which one is ideal, or when should I use these.
Thanks.
The scope resolution operator is used to access either class constants like ::const, static variables like ::$var or call static methods like ::method().
See http://php.net/manual/en/language.oop5.static.php
Static methods can be called without having an instance of the class they are defined in. They're defined in that class with the static keyword.
For example, one of CakePHP's static methods is defined like this:
class ClassRegistry {
// ...
public static function &getInstance() {
// ...
}
}
... which you can call like ClassRegistry::getInstance().
Without the static keyword, you'd need an instance of the ClassRegistry class to call that function.
You can read more here, especially about why using static methods in your own code can sometimes be a bad idea: http://kore-nordmann.de/blog/0103_static_considered_harmful.html
I am not sure how would myclass::mymethod(); work, since I use such syntax only when I am calling a STATIC class.
MyClass::DoSomething();
would call a static method named DoSomething()
while
$instance = new MyClass();
$instance->DoSomething();
would call the instance method.
I have not tested it but I believe you will run into an error if you do $instance::DoSomething()
I think the best way to understand why there is a static call and what it does behind the scene is to check this FuelPHP blog's entry: http://fuelphp.com/blog/2011/05/why-did-you-do-that
The obvious difference is that the first solution $myObject->myMethod() it's a dynamic call : you need an instance to execute myMethod().
In the second solution, MyClass::myMethod() is a static call. The class acts as a sort of namespace where a function belong. You don't need an instance for that.

php static functions vs instance functions, basics

I'm trying to learn when static functions should be used, and have had a difficult time finding an answer my questions. I am creating a class User, which is related to a class Group. If I have a user id and I want to get a user object from that, is it better to do something like
$existingUser = User::get($userId);
where the class is defined like this
class User()
{
public static function get($id){
$user = new User();
return $user->findById($id);
}
public function findById($id) {
//find and populate user object
}
}
or
$existingUser=new User();
$existingUser->findById($userId);
where the class is defined like this
class User()
{
public function findById($id) {
//find and populate user object
}
}
What about if I were to write a function which returns an array of Group objects based on a user id?
class User()
{
//stuff
$groupArray = Group::getAllByUserId($this->getId())
//stuff
}
or
class User()
{
//stuff
$group = new Group();
$groupArray = $group->findAllByUserId($this->getId());
//stuff
}
The second method creates an empty group object which is never used. Does it matter?
Am I misunderstanding the concept of static? I know it is useful for not having to instantiate a class, so if the function instantiates one anyway, does that kind of defeat the purpose? If so, what would be an example of when a static function would be used?
Anything else I should be considering in this over simplified example?
You don't need a static function int he case you show above.
Static functions are really just global functions with a namespace.
Use them when the global state of the application needs to be controlled, or if multiple copies of the function lead to inonsistant results.
Callbacks sometimes need to be static, especially if they are passed as a string.
I'm trying to learn when static functions should be used
Oh, it's so simple: never.
To understand it, read:
http://www.objectmentor.com/resources/articles/ocp.pdf
http://misko.hevery.com/code-reviewers-guide/flaw-brittle-global-state-singletons/
I find a good rule of thumb is thinking "If I don't have a [class-name], would I expect to be able to call [method-name]?"
If I don't have a user, would I expect to be able to call findByID?
Probably not. This is one of the exceptions I come across; a "load" or a "save" method sometimes makes sense to be static.
A perfect example of when to use non-static methods is (most methods in) a Database class - you should always have a database object before you try to run a query on it.
An example of when to use a static method would be a "helper" class, essentially a collection of handy functions. Say you have some methods that help you output HTML, you might have HTML::image(), HTML::url() and HTML::script(). On these, you shouldn't need a HTML object to create an image, URL, and so on.
As for stopping multiple copies of objects being created (one argument for using static methods), you should use a Singleton pattern instead (Google it) to ensure only one copy of the object ever exists.
You should probably check out this question on Active Record vs data mapper:
https://stackoverflow.com/questions/2169832/data-mapper-vs-active-record
One take from this question is that static methods on the class for loading/saving aren't really the core functionality of the class in most cases. Further, storing and loading is a kind of abstract concept that is separate from your class objects in most cases.
Isa "user" a data storage and retrieval object? In most cases, no, it is a person represented in your system that has various properties and functions. When you start tying the persistence of that object into the object, you break encapsulation and make it harder to maintain the code. What if next week you want to load your users out of memcache? It's hardly relevant to if a user can have some property or functionality.

Static or not static?

What is better to use in this context, static methods, or simple public method and call them always like this: $request = new Request();
if($request->isPostRequest()){ do smth }
ofcourse its easier to use static, but what is more properly to use?
Class Request {
public static function isSecureConnection() {}
public static function isPostRequest() {}
public static function isAjaxRequest() {}
...etc
}
If each Request is a genuine entity, then it would be better to use non-static members. But if it's not and methods are used in general, like Sinus function in math, then they'd be better to be static.
Overall it'd be better to declare static functions in a class that is just consisted of functions and no data members.
You should always create a class like if it was to be used on a non-static environment.
Then you can use that as a Singleton with lazy-instantiation. Or even as a Static class instantiation. Or even as a Standalone instance object. You decide later what to do with it.
If you start by declaring all members as static you are basically just covering a bunch of Global variables inside a glorified namespace known as a Class. You also will statically allocate the memory used by that class even if you don't call it or use it in your code.
So, just write as a Class, then you decide what to do with it. Static/Non-Static. Singleton/Instance. Factory Pattern or not. Memory Allocator X/DLL bound or whatnot.
The only exception is static members used for book-keeping in behalf of the Object Instances; things like reference counting, caches and things like that. That is the good thing about static/non-static, you can mix and match for some clever behaviors.
What if later you wanted another Request? Or what would happen if you can create more than one because you are in a multithreaded environment? Things will get really strange once you go that route with statics.
It looks like you are handling one particular request.
Now this insinuates you should make it a singleton, and/or use static functions.
Reason:
There is only one request, all the state is defined by the environment delivered to the process. The class methods are just helper functions, and you want to be able to use them without class instance.
On the other hand, you would rarely use static functions with classes that represent one of many, for example one user of many, one question of many.
Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. A property declared as static can not be accessed with an instantiated class object (though a static method can).
Example:
<?php
class Foo {
public static function aStaticMethod() {
// ...
}
}
Foo::aStaticMethod();
$classname = 'Foo';
$classname::aStaticMethod(); // As of PHP 5.3.0
?>
See the reference of Static Keyword from php.net.
If you can, use static methods as a default. static methods run quicker than their non-static counterparts.

Some instruction needed for PHP OOPS concepts

I need to clear some OOPS concepts in PHP.
Which is faster $this->method(); or self:method();
I know the concept of static keyword but can you please post the actual Use of it. Since it can not be accessed by the instance, but is there ant benefit for that?
what is factory? How can i use it?
What is singleton? How can i use that?
What is late static binding?
http://www.php.net/manual/en/oop5.intro.php
I have gone through below link but I am not getting clear with it.
1) Which is faster $this->method(); or self:method();
I set up a simple loop which calls the same method 1,000,000 times using both methods and the results are pretty much equal (in reality -> was slightly faster but by an extremely short margin)
2) I know the concept of static keyword but can you please post the actual Use of it. Since it can not be accessed by the instance, but is there ant benefit for that?
What do you mean not accessed by the instance?
public static $x;
public static function mymethod() {};
can be accessed through self::$x and self::mymethod().
There are multiple uses of static members, none of them very nice. They can be used to create singleton objects, the can be used to invoke class methods without needing to instantiate the class (for something like a bootstrap object)
3) what is factory? How can i use it?
Factories are objects used to abstract code needed to instantiate objects of a similar type. For example if you have a website which uses a hierarchy of users, each user level might have its own class. Fundamentally all the user classes will be created in the same way but there may be one or two class specific actions required.
A factory object would contain all this instantiation code and offer a simple interface to the developer. So you could use $oFactory->createUser() and $oFactory->createManager() instead of repeating yourself in multiple areas of your code.
4) What is singleton? How can i use that?
A singleton is a class that can have one and only one instance at any one time. The basic idea is that you would use a static method and a static variable to check if the object has already been instantiated.
You would use a singleton where it is important to only have one instance of a class, for example a security model may be a singleton since you want to make sure that there is only one place in your code responsible for authenticating users, a database abstraction could be a singleton if you only require one db connection (it wouldn't make sense to keep connecting to the same server and the same database for each query)
Pre-PHP5.3 singletons have some fundamental flaws since the absence of late static binding means that you can't easily extend a base singleton class.
5) What is late static binding?
Late static binding is a delay in class resolution for static methods to improve their use in OO (derived classes in particular). LSB allows self:: or __CLASS__ to resolve to the current class now instead of the class that they are defined in.
For example in earlier versions of PHP....
class parentClass {
public static function someMethod() {
echo( __CLASS__ );
}
}
class childClass extends parentClass {
}
$oObject = new childClass();
$oObject::someMethod();
would output parentClass to the browser, using LSB childClass would be output.
This is useful for many things including singletons, since the class is resolved properly it is now possible to define a singleton base class and have other objects extend it with expected results.
2) Static Key word: Unlike the methods
and data members used in OOPS where
the scope is decided by access
specifiers, the static
methods/attributes are available as a
part of the class. So it is available
to all the instance defined for the
class. To implement static keyword
functionality to the attributes or the
methods will have to be prefix with
“static” keyword. To assign values to
static variables you need to use scope
resolution operator(::) along with the
class name.
example:
< ?
class ClassName
{
static private $staticvariable; //Defining Static Variable
function __construct($value)
{
if($value != "")
{
ClassName::$staticvariable = $value; //Accessing Static Variable
}
$this->getStaticData();
}
public function getStaticData()
{
echo ClassName::$staticvariable; //Accessing Static Variable
}
}
$a = new ClassName("12");
$a = new ClassName("23");
$a = new ClassName("");
?>
Output:
12
23
23
Explanation:
* Here i have declared static variable $staticvariable
* In the constructor i am checking and value and then assigning the value
to the static variable
* Finally the getStaticData() method will output the static variable
content
1) Which is faster $this->method(); or self:method();
Answer: "self" (not $self) refers to
the type of class, where as $this
refers to the current instance of the
class. "self" is for use in static
member functions to allow you to
access static member variables. $this
is used in non-static member
functions, and is a reference to the
instance of the class on which the
member function was called.
Because "this" is an object, you use
it like: $this->member Because "self"
is not an object, it's basically a
type that automatically refers to the
current class, you use it like:
self::member
What is singleton? How can i use that? php
In software engineering, the singleton pattern is a design pattern used to implement the mathematical concept of a singleton, by restricting the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects (say, five). Some consider it an anti-pattern, judging that it is overused, introduces unnecessary limitations in situations where a sole instance of a class is not actually required, and introduces global state into an application
Example:
final class Singleton
{
protected static $_instance;
private function __construct() # we don't permit an explicit call of the constructor! (like $v = new Singleton())
{ }
private function __clone() # we don't permit cloning the singleton (like $x = clone $v)
{ }
public static function getInstance()
{
if( self::$_instance === NULL ) {
self::$_instance = new self();
}
return self::$_instance;
}
}
$instance = Singleton::getInstance();
5) What is late static binding?
Refer: Late Static Binding
What Is Factory?
refer Design Pattern
I have gone through below link but I
am not getting clear with it.
The official documentation is rich and comprehensive but some users find it hard to understand. If you are unable to grasp that, I would suggest you to go through this excellent tutorial at phpro.org (a great great resource on php topics):
Object Oriented Programming with PHP
The tutorial has been written in simple language with good real world examples, very helpful to those having problem in understanding the OOP concepts.
You are asking a pretty general question. Those are really basic concepts, so you should try to research a bit further, using also general OOP tutorials and reference.
Just to provide some hints: most of your question refer to the concept of "static". You need to understand the difference between a Class and an Instance of a class. This is the key concept.
A Class is the blueprint to create an instance. You have only one Class, but multiple Instances of it. To create an instance you use the "new" keyword, and give a name to the instance ($x = new A()); But you can have methods and fields which do not require a class instance to be run or accessed. The Class holds them, they are above any instance, they can not access any properties or methods which are not static themselves. They are useful because they can hold data and functions which are global (if you have a static variable, it'll be the same across the entire execution, wherever it is called).
I would strongly recommend you to read a couple a book on the subject. I would personally recommend PHP Object-Oriented Solutions by David Powers. This is in my opinion the best introduction to Object-Oriented coding in PHP for newcomers. You need the core knowledge before you can deploy programming patterns efficiently.
If you are really looking to understand design patterns, i would recommend Design Patterns by Christoffer G. Lasater. I've struggled to understand some of these patterns myself, and he explains them in a reasonable understandable way for the average programmer. It is written for Java, but the differences are not really that big.

Categories