在一行中实例化 Class 和声明变量

Instantiate Class and Declare Variables in One Line

有没有办法实例化一个 class 并在一行中定义变量?实例化它,然后定义所有变量,然后调用它,占用的行数几乎与原始 html 代码本身一样多。

我有一个 class 像这样:

class Gallery {
    public $image;
    public $text;
    public $heading;
    public $link;

    public function Item() {
        echo '
        <div class="gallery_item">
            <div class="gallery_image">
                <img src="' . $this->image . '">
            </div>
            <div class="gallery_text">
                <h3> ' . $this->heading . '</h3>
                <p> ' . $this->text . '</p>
                <a href="' . $this->link . '">View Live Site</a>
            </div>
        </div>
        ';
    }
}

然后我使用以下方式调用它:

<?php
            $Gallery_1 = new Gallery();
            $Gallery_1->image = "img/test.jpg";
            $Gallery_1->heading = "Test Object";
            $Gallery_1->text = "This is a sample text description for the gallery items. It can be long or short";
            $Gallery_1->link ="#";
            $Gallery_1->Item();
        ?>

我可以做下面这样的事情吗?下面的代码不起作用,但是有类似的东西吗?

$Gallery_1 = new Gallery(image->"img/test.jpg", heading->"test", text->"text", link->"#");
$Gallery_1-Item();

您可以通过在 class 中放置一个 __construct 函数来尝试这种方式。

public function __construct()
 {
    $this->image = "img/test.jpg";
    $this->heading = "Test Object";
    $this->text = "This is a sample text description for the gallery";
    $this->link ="#";    
 }

然后只需创建 图库 class,

的实例
    //will call the __construct method internally 
    $Gallery_1 = new Gallery(); 
    $Gallery_1->Item();

编辑: 根据您的评论

  public function __construct($image,$heading,$text,$link) 
  {
    $this->image = $image;
    $this->heading = $heading;
    $this->text = $text;
    $this->link =link;    
  }

  $image = "img/test.jpg";
  $heading = "Test Object";
  $text = "This is a sample text description for the gallery";
  $link ="#"; 

  $Gallery_1 = new Gallery($image,$heading,$text,$link);.
  $Gallery_1->Item();

如果您想提供自己的值,请使用您的构造函数在参数中设置属性:

class Gallery 
{
    public $image;
    public $text;
    public $heading;
    public $link;

    public function __construct($image, $text, $heading, $link) // arguments
    {
        $this->image = $image;
        $this->text = $text;
        $this->heading = $heading;
        $this->link = $link;
    }

    public function Item()
    // rest of your codes

这样当你实例化时,只需填写参数:

$gallery = new Gallery('img/test.jpg', 'test', 'text', 'link#');
$gallery->Item(); // echoes the html markup,