Alex
Alex

Reputation: 4774

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!

Upvotes: 37

Views: 53192

Answers (4)

Jose
Jose

Reputation: 168

Send the class name as string parameter you need use the namespace. For example:

function defineClass()
{
  $class = "App\MyClass"; // mention the namespace too
}

function reciveClass($class)
{
   $class:: // what do you need,
}

Upvotes: 1

kije
kije

Reputation: 407

In PHP, classes (or class names) are handled as strings. Since PHP 5.5, you can use YourClass::class to get a fully qualified class name. If you want to get it in an earlier version of php, you can (if you have already an object of the calss) either do the following:

<?php
$obj = new YourClass();
// some code

$clazz = get_class($obj);
?>

or, you can implement a static method in your class, like this:

<?php

class YourClass {
    // some code

    public static function getClassName() {
        return get_called_class();
    }
?>

If you want to pass a class to a function, you can do it like this:

<?php
function do_somthing($arg1, $clazz) {
    $clazz::someStaticMethod($arg1);
}
?>

or

<?php
function do_somthing($arg1, $clazz) {
    call_user_func(array($clazz, 'someStaticMethod')), $arg1);
}
?>

If you need to call a non-static method of that class, you need to instanciate it:

<?php
function do_somthing($arg1, $clazz) {
    $obj = new $clazz(); 
    $obj->someNonStaticMethod();
}
?>

Note: You can use PHP type hinting with passed class names:

<?php
function do_somthing($arg1, MyInterface $clazz) {
    $obj = new $clazz(); 
    $obj->someInterfaceMethod();
}
?>

Upvotes: 17

CntkCtn
CntkCtn

Reputation: 357

I think you can.

Send the class name as string parameter then use it like below.

$classtr = "yourparam";// param comes from the function call.

$obj = new $classtr;
$obj->method();

Upvotes: 4

Joseph Silber
Joseph Silber

Reputation: 219930

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

Upvotes: 56

Related Questions