Php class method as argument

Php class method as argument

To experiment on performance of pass-by-reference and pass-by-value, I used this script. Conclusions are below.

#!/usr/bin/php
function sum ( $array , $max ) < //For Reference, use: "&$array"
$sum = 0 ;
for ( $i = 0 ; $i < 2 ; $i ++)#$array[$i]++; //Uncomment this line to modify the array within the function.
$sum += $array [ $i ];
>
return ( $sum );
>

$max = 1E7 //10 M data points.
$data = range ( 0 , $max , 1 );

$start = microtime ( true );
for ( $x = 0 ; $x < 100 ; $x ++)$sum = sum ( $data , $max );
>
$end = microtime ( true );
echo «Time: » .( $end — $start ). » s\n» ;

/* Run times:
# PASS BY MODIFIED? Time
— ——- ——— —-
1 value no 56 us
2 reference no 58 us

3 valuue yes 129 s
4 reference yes 66 us

1. PHP is already smart about zero-copy / copy-on-write. A function call does NOT copy the data unless it needs to; the data is
only copied on write. That’s why #1 and #2 take similar times, whereas #3 takes 2 million times longer than #4.
[You never need to use &$array to ask the compiler to do a zero-copy optimisation; it can work that out for itself.]

Читайте также:  PHP Program to show current page URL

2. You do use &$array to tell the compiler «it is OK for the function to over-write my argument in place, I don’t need the original
any more.» This can make a huge difference to performance when we have large amounts of memory to copy.
(This is the only way it is done in C, arrays are always passed as pointers)

3. The other use of & is as a way to specify where data should be *returned*. (e.g. as used by exec() ).
(This is a C-like way of passing pointers for outputs, whereas PHP functions normally return complex types, or multiple answers
in an array)

5. Sometimes, pass by reference could be at the choice of the caller, NOT the function definitition. PHP doesn’t allow it, but it
would be meaningful for the caller to decide to pass data in as a reference. i.e. «I’m done with the variable, it’s OK to stomp
on it in memory».
*/
?>

Источник

Passing an Instance Method as Argument in PHP

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); >);

Accept function as parameter in PHP

It’s possible if you are using PHP 5.3.0 or higher.

See Anonymous Functions in the manual.

In your case, you would define exampleMethod like this:

function exampleMethod($anonFunc) //execute anonymous function 
$anonFunc();
>

Pass instance of model in method parameter

Branch::class is a class constant that returns the class name as a string, as the error message suggests. Perhaps you’re looking to pass new Branch instead.

Pass method with argument to other class method

A method of an instantiated object is passed as an array containing an object at index 0 and the method name at index 1.

class Foo /* extends Database */ private $crumb = 'Hello';

public function breadcrumb( callable $translate ) return $translate($this->crumb);
>
>

class Bar /* extends Database */ private $translation = ['Hello'=>'Hallo'];

public function translate($word) return $this->translation[$word];
>
>

$foo = new Foo;
$bar = new Bar;
echo $foo->breadcrumb( [$bar, 'translate'] ); ?>

(you also forgot the $this-> reference for accessing the instance memeber translation .)

Passing a class as function parameter

You can use the magic ::class constant:

public function uniqueSlug($str, $model)
$slug = Str::slug($str);

$count = $model::whereRaw("slug RLIKE '^(-4+)?$'")->count();

return $count ? "-" : $slug;
>

$newcat->slug = $helper->uniqueSlug($appname, Apk::class);

Passing static methods as arguments in PHP

The ‘php way’ to do this, is to use the exact same syntax used by is_callable and call_user_func.

This means that your method is ‘neutral’ to being

  • A standard function name
  • A static class method
  • An instance method
  • A closure

In the case of static methods, this means you should pass it as:

myFunction( [ 'MyClass', 'staticMethod'] );

or if you are not running PHP 5.4 yet:

myFunction( array( 'MyClass', 'staticMethod') );

Passing a class, method and arguments to WordPress functions

You should be able to pass an anonymous function instead, whose body would simply call the bar method with the appropriate arguments.

The anonymous function would look like this:

Or alternatively, if you’re using PHP 7.4+:

So, just pass that as the callback, like this:

add_menu_page( 
$page_title,
$menu_title,
$capability,
$menu_slug,
// fn() => $this->bar('Bob'),
function () <
$this->bar('Bob');
>,
$icon_url,
$position
);

Note: I’m very unfamiliar with WordPress so this might not be the most appropriate way to do this.

Источник

Passing static methods as arguments in php

One solution using this supported callback type is to define a single-use class that essentially acts like a closure type: Solution 3: Assuming you’ve access to objects and static (PHP 5 or greater), you can create an object and pass the arguments directly there, like so: Assuming you don’t have access to objects/static; you could just do a global: Solution 1: What you’re actually doing there is passing an object, not a class. As a sidenote, you are ending with this portion of code : Quoting the manual page for (which is the same as die) (emphasis mine)

Passing parameters to a static method with PHP

This is rather odd, as it should work ; after testing this portion of code :

Which indicates the static method did indeed receive the parameter (and I see no reason why it shouldn’t, actually).

As a sidenote, you are ending with this portion of code :

Quoting the manual page for exit (which is the same as die) (emphasis mine) :

void exit ([ string $status ] ) void exit ( int $status ) 

If status is a string, this function prints the status just before exiting.
If status is an integer, that value will also be used as the exit status.
[. ]
Note: PHP >= 4.2.0 does NOT print the status if it is an integer.

You are using PHP 5.3, which is a more recent version than 4.2 ; and, in your case, $status is an integer — which means it is perfectly normal to not have anything displayed, with the code your posted.

And, to finish : if you remove the die , your code ends up doing this :

if(!filter_var($index, FILTER_VALIDATE_INT))

filter_var returns the filtered value ; using FILTER_VALIDATE_INT , I suppose you are filtering to get an integer — and 0 is integer.

Which means your call to filter_var will return 0 .

0 is considered as false (see Converting to boolean) — so, you will enter into the if block ; and the exception will be thrown.

Considering filter_var returns :

  • The filtered data,
  • or false when the filter failed,
  • And that 0 is a valid data that can be returned,

You should probably use the === operator (see Comparison Operators) , to compare the returned value to false . Which means some code that would look like this :

if(filter_var($index, FILTER_VALIDATE_INT) === false)

Function — Passing method as parameter in PHP, Passing method as parameter in PHP [duplicate] Ask Question Asked 8 years, 10 months ago. Modified 8 years, 10 months ago. Viewed 8k times 12 1. This question already has answers here: Passing an instance method as argument in PHP (3 answers) Closed 8 years ago. I have a class in PHP like this:

Call static function with parameter as a callback

Thanks to @MichaelBerkowski

Mustache_Engine(array('escape' => array('SampleClass','escapeMustache')) 

Passing static methods as arguments in PHP, The ‘php way’ to do this, is to use the exact same syntax used by is_callable and call_user_func. This means that your method is ‘neutral’ to being. A standard function name. A static class method. An instance method. A closure. In the case of static methods, this means you should pass it as: myFunction ( [ ‘MyClass’, ‘staticMethod’] ); Code samplefunction myFunction( $method ) myFunction( function() < return MyClass::staticMethod(); >);Feedback

Pass extra parameters to usort callback

I think this question deserves an update. I know the original question was for PHP version 5.2, but I came here looking for a solution and found one for newer versions of PHP and thought this might be useful for other people as well.

For PHP 5.3 and up, you can use the ‘ use ‘ keyword to introduce local variables into the local scope of an anonymous function. So the following should work:

function sort_by_term_meta(&$terms, $meta) < usort($terms, function($a, $b) use ($meta) < $name_a = get_term_meta($a->term_id, 'artist_lastname', true); $name_b = get_term_meta($b->term_id, 'artist_lastname', true); return strcmp($name_a, $name_b); >); > 

Some more general code

If you want to sort an array just once and need an extra argument you can use an anonymous function like this:

usort($arrayToSort, function($a, $b) use ($myExtraArgument) < //$myExtraArgument is available in this scope //perform sorting, return -1, 0, 1 return strcmp($a, $b); >); 

If you need a reusable function to sort an array which needs an extra argument, you can always wrap the anonymous function, like for the original question:

In PHP, one option for a callback is to pass a two-element array containing an object handle and a method name to call on the object. For example, if $obj was an instance of class MyCallable , and you want to call the method1 method of MyCallable on $obj , then you can pass array($obj, «method1») as a callback.

One solution using this supported callback type is to define a single-use class that essentially acts like a closure type:

function sort_by_term_meta( $terms, $meta ) < usort($terms, array(new TermMetaCmpClosure($meta), "call")); >function term_meta_cmp( $a, $b, $meta ) < $name_a = get_term_meta($a->term_id, $meta, true); $name_b = get_term_meta($b->term_id, $meta, true); return strcmp($name_a, $name_b); > class TermMetaCmpClosure < private $meta; function __construct( $meta ) < $this->meta = $meta; > function call( $a, $b ) < return term_meta_cmp($a, $b, $this->meta); > > 

Assuming you’ve access to objects and static (PHP 5 or greater), you can create an object and pass the arguments directly there, like so:

 static function cmp_method($a, $b) < $meta = self::$meta; //access meta data // do comparison here >> // then call it SortWithMeta::sort($terms, array('hello')); 

Assuming you don’t have access to objects/static; you could just do a global:

$meta = array('hello'); //define meta in global function term_meta_cmp($a, $b) < global $meta; //access meta data // do comparison here >usort($terms, 'term_meta_cmp'); 

Php — How to use class methods as callbacks, You’re correct, I didn’t think about passing the arguments across. But unless I’m reading it wrong, the way you’ve specified you …

Pass PHP Class as Parameter

What you’re actually doing there is passing an object, not a class.

creates an instance of SampleClass, aka an object.

I assume there’s some error being thrown elsewhere as what you have is correct. I tested the following code and got the expected output:

class SampleClass < public function getValue() < return 4; >> $sc = new SampleClass(); SampleFunction($sc); function SampleFunction(&$refClass) < echo $refClass->getValue(); > 

If you provide more details of your actual code we might be able to determine the problem.

I can’t see anything wrong with your code

using &$refClass is however is not recommended and I guess willbe removed from future iteration of PHP version

class objects are passed as reference I suppose so no need of ‘&’

Why is the function argument a reference? Probably shouldn’t be.

Other than that, there’s nothing wrong with you posted, so the error is likely within SampleClass .

PHP Static Properties and Methods, The static method is called by name of class along with scope resolution operator In following example, the class has a static property $count that increnments every time constructor is executed (i.e. for each object). Inside the class, there is a static function that retrieves value of static property Example …

Источник

Оцените статью