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

时间:2015-04-11 02:22:32

标签: php class instantiation

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

我有一个类似的课程:

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();

2 个答案:

答案 0 :(得分:2)

您可以通过在班级中添加__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 ="#";    
 }

然后只需创建图库类的实例,

    //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();

答案 1 :(得分:2)

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

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,