开发者

Returning a static Class in PHP

I am working on a backend project. I need 开发者_开发问答to return a static object withing another static object:

Class this_is_a_very_long_class_name
{
    public static function call()
    {
        return self;
    }

    public static function script_link($link)
    {
        //doing stuff here...
    }
}

Class Main
{
    public static function view()
    {
        // trying to return View object
        return this_is_a_very_long_class_name::call();
    }
}

and I am trying to use it like this:

Main::view()::script_link('Some script');

So how can I accomplish that?

P.S.: I am not looking for another solution. I am looking for a answer what I asked.


You don't need that.

Use

View::script_link();

Also this is wrong and misleading view()->script_link because script_link is static

Addendum

If you your problem is your class name length I suggest you to create simple wrapper for this.

function createLink($string){
 return VERY_LONG_CLASS_NAME_HELLO_PHP_NAMESPACE::script_link($string);
}

this way you just need to createLink();


in php 5.3: return new View(); (instead of return View::self;).
Manual: http://php.net/manual/en/language.oop5.basic.php#example-159


in php 5.2 use ReflectionClass


I think your syntax on the call is wrong. Since it is static, what you are trying to do would look something like this:

Main::view()::script_link('Some script');

Except that would give you a syntax error. Also, since it is static, you don't need to return anything. You should make it two separate calls:

Main::view();
View::script_link("Some script");

It makes no sense to say "I need to return a static object". If the class is defined, then the static object is present and can be accessed.


You just need a variable to hold the class, as a direct call is invalid syntax Sample:

Class Main
{
    public static function view($type)
    {
        // return some class
        switch ($type) {
            case "View 2": 
                return View2;
                break;
            default:
                return View;
        }
    }
}

$v = Main::view("normal view");
$v::script_link('test');


Are you looking for functionality as late static binding? Which is supported from PHP 5.3. See here: http://php.net/manual/en/language.oop5.late-static-bindings.php

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜