PHP构造函数未调用

I have problem, can i call constructor without create 'new class()' ? Or you maybe have another way for this :

<?php

class a
{
    public static $hello;

    public function say()
    {
        return self::$hello;
    }

}

class b extends a
{
    public function __construct()
    {
        self::$hello = 'hello world';
    }
}


echo b::say();

?>

I have try with :

$b = new b();
echo $b->say();

And it's work. But i want to use b::say();

Can help me?

Thank you!!

Yes it is possible just make the say() function static like this :

public static function say()
{
    return self::$hello;
}

Declaring class methods as static makes them accessible without needing an instantiation of the class.

This example looks to me like late static binding. So try changing that return self::$hello; into return static::$hello;

Check out this. Is this good for you?

<?php

class a {
    public static $hello;

    public static function say() {
        return self::$hello;
    }
}

class b extends a {
    public function __construct() {
        self::$hello = 'hello world';
    }

    public static function factory() {
        return new b();
    }
}

echo b::factory()->say();

?>

Actually I couldn't find a way to do this without calling constructor. This is how the workaround looks like. factory is just a name. you can rename it.

calling class method (with constructors) without object instantiation in php

You have asked: "can i call constructor without create 'new class()' ?"
The answer: No.

... Classes which have a constructor method call this method on each newly-created object

You have requested "But i want to use b::say();"
b::say(); - is call of static method.
You can't override non-static parent method to static. But you can restructure your base class class a to make say() method static.

<?php

class a
{
  public static $hello;

public static function say()
{
  return self::$hello;
}

}

class b extends a
{
public function __construct()
  {
      self::$hello = 'hello world';
  }
}

The thing that you were missing was you needed to add your content to your new class method. - Just call it like so:

$b = new b('Some words');
echo $b->say();

When calling a new class and using a constructor - You will want to add the content in the paramaters for the new class you are making.

It acts as if you are calling the __construct function. - Calling new class($a) will call the __construct($a) function once making the object.

Hope that this helped a bit :)