Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a class as function parameter

I'm trying to do something like this:

function doSomething($param, Class) { Class::someFunction(); }  $someVar = doSomething($param, Class); 

Is it possible?

To explain better what I'm trying to do. I have a helper function in Laravel to generate unique slugs, so I have to query different tables depending on where the slug is going to be saved.

Actual code I'm trying to write:

$newcat->slug = $helper->uniqueSlug($appname, Apk);  public function uniqueSlug($str, Apk)     {         $slug = Str::slug($str);          $count = Apk::whereRaw("slug RLIKE '^{$slug}(-[0-9]+)?$'")->count();          return $count ? "{$slug}-{$count}" : $slug;     } 

Thanks!

like image 398
Alex Avatar asked Sep 16 '15 17:09

Alex


People also ask

Can we pass class as function arguments?

Passing and Returning Objects in C++ In C++ we can pass class's objects as arguments and also return them from a function the same way we pass and return other variables. No special keyword or header file is required to do so.

Can you pass a class to a function?

yes of coarse you can pass classes or functions or even modules ...

Can we pass class as parameter in Java?

We can pass Object of any class as parameter to a method in java. We can access the instance variables of the object passed inside the called method. It is good practice to initialize instance variables of an object before passing object as parameter to method otherwise it will take default initial values.

Can we pass class objects as function arguments in Python?

You can pass an object as an argument to a function, in the usual way.


1 Answers

You can use the magic ::class constant:

public function uniqueSlug($str, $model) {     $slug = Str::slug($str);      $count = $model::whereRaw("slug RLIKE '^{$slug}(-[0-9]+)?$'")->count();      return $count ? "{$slug}-{$count}" : $slug; }  $newcat->slug = $helper->uniqueSlug($appname, Apk::class); 
like image 193
Joseph Silber Avatar answered Sep 20 '22 08:09

Joseph Silber