Passing a class as a function parameter

I am trying to do something like this:

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

$someVar = doSomething($param, Class);

Is it possible?

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

The actual code I'm trying to write is:

$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!

+4
source share
3 answers

You can use the magic constant ::class:

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);
+11
source

PHP ( ) . PHP 5.5, YourClass::class, . php, ( calss) :

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

$clazz = get_class($obj);
?>

, :

<?php

class YourClass {
    // some code

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

, :

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

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

, :

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

.. PHP :

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

, .

, , .

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

$obj = new $classtr;
$obj->method();
+2
source

Source: https://habr.com/ru/post/1607695/


All Articles