Call static function by method name? [duplicate] - php

This question already has answers here:
Dynamic static method call in PHP?
(9 answers)
Closed 6 years ago.
I have a couple of methods whose returns are being cached, and the cache key is the name of the method itself.
For instance, if this is my class
class tester {
static function test() {
$data = build_data();
cache(__METHOD__, $data);
}
}
The cache key value is tester::test.
I am implementing functionality to warm the cache. If I have all the cache keys, I could just call them one by one.
foreach ( $keys as $key ) {
$key();
}
But apparently, I can't call a string like 'tester::test' in this manner
Fatal error: Call to undefined function tester::test() ...
Do I have to do string parsing, to pull apart the class name and method, and then call them like $class::$method()? Or is there a simpler way to do it?

Thanks to Michael Lihs for linking the question in their comment; it turns out that call_user_func() does what I'm looking for.

Related

What does the Interface object means in the function parameters [duplicate]

This question already has answers here:
Why is type hinting necessary in PHP?
(6 answers)
Closed 4 years ago.
I am not able to understand what is the meaning of having any model or interface object into the method parameters.
For example,
public function checkRights(CommentInterface $comment)
{
return true;
}
so here what does CommentInterface do? why we are not only passing $comment here? How do you name this kind of thing in programming language?
I am new to object oriented php
Thanks.
This is called as Type Hinting.
Type hinting forces you to only pass objects of a particular type. This prevents you from passing incompatible values, and creates a standard if you're working with a team etc.,
check the following example:
class Profile {
private $setting;
public function __construct(Setting $setting)
{
$this->setting = $setting;
}
}
Because we need to use the $setting object inside the function, we inject/pass/type-hint it as a parameter.

use a function after a function PHP OOP [duplicate]

This question already has answers here:
PHP method chaining or fluent interface?
(10 answers)
Closed 4 years ago.
i have a simple question in OOP
I've see in a lot of frameworks like Laravel something like this :
$data = Model::OrderBy('id','desc')->skip(5)->take(10)->get()->toArray();
My Question is, how can i can call a function after another function ?
Exemple :
class test{
public function test1(){}
public function test2(){}
}
how i can call the function test 2 after test 1 like that test1()->test2()
i hope the question is clear
In its simplest form you just have to return the current instance in all your chainable methods:
return this;
Often these chained methods return a new object instead of altering the current one though - this is called immutability or immutable objects.

PHP declaring object as array for function parameter [duplicate]

This question already has an answer here:
PHP array of non-primitive class as function parameter
(1 answer)
Closed 4 years ago.
I'm quite new with PHP. I'm having problems declaring an object as array for function parameter. In Java, I simply use public void methodName (List<Object> listVariableName){} for passing a list of many Objects.
I did some research in PHP and one of the answers suggested to put array in method parameter declaration like so function myFunction($a, array Object $obj){}
Currently, I have a class named Lesson
class Lesson implements JsonSerializable{
private $lessonId;
private $lessonNo;
private $lessonTitle;
private $isLessonActive;
private $isLessonRemoved;
//getters and setter here....
}
Then I'm trying to declare a method called addTopicLesson
function addTopicLesson(Topic $topic, array Lesson $lesson){
}
But, I'm getting an error in array Lesson $lesson
There's 1 topic and MANY lessons. How can I go about implementing or defining the method signature?
I found this but I'd like to know if there's a better approach than to call itself.
I'd appreciate any suggestion.
Thank you.
List<T> is not an array. It's a list utilizing generic type mechanism.
There are no generics in PHP. You can only typehint an array but you cannot control what's inside it at the level of method declaration.
function addTopicLesson(Topic $topic,array $lessons)
{
foreach($lessons as $lesson)
{
addLesson($page);
}
}
function addLesson(Lesson $lesson)
{
}

Passing method as parameter in PHP [duplicate]

This question already has answers here:
Passing an instance method as argument in PHP
(3 answers)
Closed 9 years ago.
I have a class in PHP like this:
class RandomNumberStorer{
var $integers = [];
public function store_number($int){
array_push($this->integers, $int);
}
public function run(){
generate_number('store_number');
}
}
...elsewhere I have a function that takes a function as a parameter, say:
function generate_number($thingtoDo){
$thingToDo(rand());
}
So I initialise a RandomNumberStorer and run it:
$rns = new RandomNumberStorer();
$rns->run();
And I get an error stating that there has been a 'Call to undefined function store_number'. Now, I understand that that with store_number's being within the RandomNumberStorer class, it is a more a method but is there any way I can pass a class method into the generate_number function?
I have tried moving the store_number function out of the class, but then I then, of course, I get an error relating to the reference to $this out of the context of a class/ instance.
I would like to avoid passing the instance of RandomNumberStorer to the external generate_number function since I use this function elsewhere.
Can this even be done? I was envisaging something like:
generate_number('$this->store_number')
You need to describe the RandomNumberStore::store_number method of the current instance as a callable. The manual page says to do that as follows:
A method of an instantiated object is passed as an array containing an
object at index 0 and the method name at index 1.
So what you would write is:
generate_number([$this, 'store_number']);
As an aside, you could also do the same in another manner which is worse from a technical perspective, but more intuitive:
generate_number(function($int) { $this->store_number($int); });

Shorthand new Instance->Method syntax in PHP? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP: How to chain method on a newly created object?
I can create an instance and call it's method via:
$newObj = new ClassName();
$newObj -> someMethod();
But is there any way I can do it in a shorter notation, an anonymous instance? I tried this:
(new ClassName())->someMethod();
But it doesn't seem to work as expected.
Additional Info: The method I want to call is public but not static.
PHP 5.4 supports it.
If you can't update you can workaround like this:
function yourclass($param) {
return new yourclass($param);
}
yourclass()->method();
Don't forget that your constructor must return $this;
Not that i know of.
But! - You could implement a Singleton Pattern and then call:
ClassName::getInstance()->someMethod();
Or, to cut it short ;)
ClassName::gI()->someMethod();
If someMethod does not refer to $this, you could also simply call it as a static function, though it wasn't defined as one:
ClassName::someMethod();
If the method is static and doesn't rely on any class variables (maybe you've put it in a class just for organisation purposes), you can simply call it staticly as phil is demonstrating with getInstance:
ClassName::someMethod()

Categories