Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a static method from a class in another namespace in PHP

This code bellow gives me this error : Class 'MyNamespace\Database' not found. How do I reference a class that belongs to no namespace, from inside one ?

Class Database
{
    public function request()
    {
    }
}

namespace MyNamespace
{
    class MyClass
    {
        public function myFuction()
        {
            Database::request();
        }
    }
}
like image 384
Thomas Joulin Avatar asked Jul 05 '11 07:07

Thomas Joulin


People also ask

How can we call static method from another static method in PHP?

$this::staticMethod(); Since PHP 5.3 you can use $var::method() to mean <class-of-$var>:: ; this is quite convenient, though the above use-case is still quite unconventional. So that brings us to the most common way of calling a static method: self::staticMethod();

Can we call static method with object in PHP?

Static properties are accessed using the Scope Resolution Operator ( :: ) and cannot be accessed through the object operator ( -> ). It's possible to reference the class using a variable. The variable's value cannot be a keyword (e.g. self , parent and static ).

Can static methods be inherited in PHP?

The static variable is used in the A and B classes, yet the method is inherited so it is actually the same code which is called. Until PHP 8.0, there would be a distinct static variable depending on which class is called.

Can a class be static in PHP?

In PHP, we can have both static as well as non-static (instantiated) classes. Introduction: A static class in PHP is a type of class which is instantiated only once in a program. It must contain a static member (variable) or a static member function (method) or both.


1 Answers

Try with

\Database::request();

Also see Namespace Basics Example 1 in the PHP Manual

like image 194
Gordon Avatar answered Oct 16 '22 05:10

Gordon