Is it possible to declare a method static and nonstatic in PHP?
Can I declare a method in an object as both a static and non-static method with the same name that calls the static method?
I want to create a class that has a static method «send» and a non-static method that calls the static function. For example:
I want to be able to call the function on these two was
5 Answers 5
You can do this, but it’s a bit tricky. You have to do it with overloading: the __call and __callStatic magic methods.
This isn’t an ideal solution, as it makes your code harder to follow, but it will work, provided you have PHP >= 5.3.
No you can’t have two methods with the same name. You could do basicly the same thing by renaming one of the methods. Renaming test::send(«Hello World!»); to test::sendMessage(«Hello World!»); would work. I would just create the a single send method with an optional text argument that changes how the method functions.
I courious as to why you need the static function at all.
I would make a hidden class as the constructor and return that hidden class inside the parent class that has static methods equal to the hidden class methods:
To call it statically:
To call it dynamically:
I agree that this should be avoided at all costs but there are some cases where it might be useful.
In most cases it will just make your code unreadable and unmanageable.
Believe me, I have been down that path.
Here is an example with a use case scenario where it might still be practical.
I am extending CakePHP 3.0’s File class as my default file handling class.
I wanted a to put in a static mime type guesser.
In some cases I have a filename instead of an actual file and some assumptions need to be made in this case. ( if the file exists, try to get the mime from it else use extention of filename provided)
Other times if I actually instantiated an object the default mime() method should work but if it fails the filename needs to be extracted from the object and the static method should be called instead.
To avoid confusion my aim was to get the mime type by calling the same method:
Static:
As object
Here is my example extended class:
Ошибка Cannot make static method CAllEventMessage::GetList() non static in class CEventMessage
Всех с Новым Годом!
Пытался сделать обновление платформы и получил ошибку после которой сайт переходит в нерабочее состояние.
Fatal error: Cannot make static method CAllEventMessage::GetList() non static in class CEventMessage in \bitrix\modules\main\classes\mysql\event.php on line 125
Может кто нибудь помочь с этой проблемой?
Версия php 5.6. При попытке повысить версию до 7.0.X, система обновления в самом начале выдает ошибку:
Fatal error: Uncaught TypeError: Argument 1 passed to Bitrix\Main\Diag\ExceptionHandler::handleException() must be an instance of Exception, instance of Error given in \bitrix\modules\main\lib\diag\exceptionhandler.php:167
| Цитата |
|---|
| Евгений Жуков написал: Понизьте версию до php 5.3, обновитесь и верните обратно php 5.6 |
Спасибо огромное! Локальная копия сайта обновилась с понижением до php 5.3 не полностью и некоторые обновления выдавали ошибку. Но по завершению установки обновлений осталось только 13 неустановленных. После повышения обратно до версии php 5.6 удачно установились и эти 13 обновлений. Теперь имею полностью обновленную локальную копию сайта.
Еще раз огромное спасибо, Евгений!
| Цитата |
|---|
| Евгений Жуков написал: Сделайте проверку сайта после обновления, чтобы быть уверенным, что все файлы обновлены. В случае возникновения ошибок рекомендую все же обратиться в техподдержку. |
Спасибо. Вы имеете ввиду штатную проверку сайта( Полное тестирование системы )?
Скажите а будет ли рабочим вариант: накатить обновление на локальной копии и затем обновленный сайт забекапить, после чего на боевом сервере его восстановить. Что будет с папкой upload которую бекапить просто бессмысленно ввиду большого размера?
Просто, насколько я понял, у меня не получится каким-нибудь простым способом установить php 5.3.29 на сервере (может ошибаюсь, но, кажется, нужно собирать из исходников ).
Может быть будут еще какие-нибудь мудрые советы?
When should I use static methods?
I have a class that is containing 10 methods. I always need to use one of those methods. Now I want to know, which approach is better?
5 Answers 5
It is an interesting subject. I’m gonna give you a design oriented answer.
In my opinion, you should never use a static class/function in a good OOP architecture.
When you use static, this is to call a function without an instance of the class. The main reason is often to represent a service class which should not be instantiated many times.
I will give you 3 solutions (from the worst to the best) to achieve that:
Static
A static class (with only static functions) prevent you from using many OOP features like inheritance, interface implementation. If you really think of what is a static function, it is a function namespaced by the name of its class. You already have namespaces in PHP, so why add another layer?
Another big disadvantage is that you cannot define clear dependencies with your static class and the classes using it which is a bad thing for maintenability and scalability of your application.
Singleton
A singleton is a way to force a class to have only one instance:
It is a better way because you can use inheritance, interfaces and your method will be called on an instanciated object. This means you can define contracts and use low coupling with the classes using it. However some people consider the singleton as an anti pattern especially because if you want to have 2 or more instances of your class with different input properties (like the classic example of the connection to 2 different databases) you cannot without a big refactoring of all your code using the singleton.
Service
A service is an instance of a standard class. It is a way to rationalize your code. This kind of architecture is called SOA (service oriented architecture). I give you an example:
It is a good idea to use a framework helping you to inject them into each others (dependency injection) in order to use them at their full potential. In the PHP community, you have a nice example of implementation of this in Symfony for instance.
If you do not have a framework, singletons are certainly an option even if I personally prefer a simple file where I make manual dependency injection.
If you have a framework, use its dependency injection feature to do that kind of thing.
You should not use static method (in OOP). If you need a static method in one of your class, this means you can create a new singleton/service containing this method and inject it to the instance of classes needing it.
How can I call a static method on a variable class?
I’m trying to make some kind of function that loads and instantiates a class from a given variable. Something like this:
If I use it like this:
It should include and instantiate the session class.
BTW: the static getInstance function comes from this code:
The thing is that right now the way to use the functions in a class is this:
6 Answers 6
Calling static functions on a variable class name is apparently available in PHP 5.3:
Could definitely use that right now myself.
Until then you can’t really assume that every class you are loading is designed to be a singleton. So long as you are using
The first argument is a callback type containing the classname and method name in this case.
Why not use __autoload() function?
then you just instantiate object when needed.
It looks like you are fighting PHP’s current implementation static binding, which is why you are jumping through hoops with getCallingClass. I can tell you from experience, you should probably abandon trying to put instantiation in a parent class through a static method. It will cause you more problems in the end. PHP 5.3 will implement «late static binding» and should solve your problem, but that obviously doesn’t help now.
You are probably better off using the autoload functionality mentioned by kodisha combined with a solid Singleton implementation. I’m not sure if your goal is syntactic sugar or not, but it think you will do better in the long run to steer clear of trying to save a few characters.
Off the top of my head, needs testing, validation etc:
Late static bindings will work for you I think. In the construct of each class do:
Then. Here is an autoloader I created. See if this solves your dilemma.
Then all you have to do is
but you have to have a php file in the path with the name ClassName.php where ClassName is the same as the name of the class you want to instantiate.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.16.40224
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
How to call non-static method from static method of same class?
I am working on PHP code.
Here is the sample code to explain my problem:
Note: Both functions are used throughout the site, which is not known. I can’t make any changes in the static/non-static nature of them.
3 Answers 3
You must create a new object inside the static method to access non-static methods inside that class:
The result would be non-static
Later edit: As seen an interest in passing variables to the constructor I will post an updated version of the class:
The main difference would be that you can call static methods for a class without having to instantiate an object of that class. So, in your static method try
But I don’t see how this would make any sense in any context.
Asnwer selcted as correct solves problem. There is a valid use case (Design Pattern) where class with static member function needs to call non-static member function and before that this static members should also instantiate singleton using constructor a constructor.
Case: For example, I am implementing Swoole HTTP Request event providing it a call-back as a Class with static member. Static Member does two things; it creates Singleton Object of the class by doing initialization in class constructor, and second this static members does is to call a non-static method ‘run()’ to handle Request (by bridging with Phalcon). Hence, static class without constructor and non-static call will not work for me.
Not the answer you’re looking for? Browse other questions tagged php oop or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.16.40224
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.



