Luuk Wuijster
Luuk Wuijster

Reputation: 6878

OOP PHP - Call method from extended class without having to put the class for it

I have a class in a file like:

class foo
{
    public function something()
    {
        return "something"
    }
}

Then in an other file I have a class like:

class bar extends foo
{

}

Now I want to call the something method. I can do this like foo::something();, but I want to just do something(). just like it is in Laravel.

Ofcourse I can require the file where foo is in, but I dont want that, because I think thats kind of dirty.

So, how do I do that? I've looked around on the internet but did not find an answer. Everthing I find is from like 5-7 years ago.

EDIT:

Look, you just return view();

Without self:: or this->

And I am wondering how you do that. IN VANILLA PHP

public function index()
{

    $categories = Category::categories();
    $posts = Post::latest()->get();

    return view('welcome', compact('posts', 'categories'));
}

Upvotes: 1

Views: 532

Answers (1)

Alexey Mezenin
Alexey Mezenin

Reputation: 163858

These functions are called global helpers. You can create your own Laravel helpers in custom helpers file. Helper could be wrapper for some class method or a simle function:

if (! function_exists('customHelper')) {
    function customHelper()
    {
        return 'Something';
    }
}

To make custom helpers file work add it to autoload section of an app's composer.json and run composer dumpauto command once:

"autoload": {
    ....
    "files": [
        "app/someFolder/helpers.php"
    ]
},

Upvotes: 2

Related Questions