0

为什么我的班级不画画?如果我让它成为它运行的唯一函数,但在类中它不起作用:(。我是 PHP 类的新手(Java 类对我来说不是新的)。

<?php

class Schild
{

    public function __construct(){
        $text = $_GET['text'];
        $picture = imagecreatefrompng("bild.png");
        $pika = imagecreatefromjpeg("pika.jpg");
        $pika_size = getimagesize("pika.jpg");
    }

    public function drawPicture()
    {
        $im = imagecolorallocate ($picture, 255, 0, 255);
        imagettftext($picture, 111, 0, 100, 100,$im , "Marmellata(Jam)_demo.ttf", $text);

        # int ImageCopy ( resource $dst_im , resource $src_im , int $dst_x , int $dst_y , int $src_x , int $src_y , int $src_w , int $src_h )
        imagecopy($picture, $pika, 50, 50, 0, 0, $pika_size[0], $pika_size[1]);

        $zufall = rand(1,99999999);

        #header("Content-Type: image/jpeg");
        imagejpeg($picture);
        imagedestroy($picture);

    }
}

$schild1 = new Schild();
$schild1->drawPicture();
?>
4

1 回答 1

3
<?php

class Schild
{
    protected $picture;
    protected $pika;
    protected $pika_size;
    protected $text;

    public function __construct(){
        $this->text = $_GET['text'];
        $this->picture = imagecreatefrompng("bild.png");
        $this->pika = imagecreatefromjpeg("pika.jpg");
        $this->pika_size = getimagesize("pika.jpg");
    }

    public function drawPicture()
    {
        $im = imagecolorallocate ($this->picture, 255, 0, 255);
        imagettftext($this->picture, 111, 0, 100, 100,$im , "Marmellata(Jam)_demo.ttf", $this->text);

        # int ImageCopy ( resource $dst_im , resource $src_im , int $dst_x , int $dst_y , int $src_x , int $src_y , int $src_w , int $src_h )
        imagecopy($this->picture, $this->pika, 50, 50, 0, 0, $this->pika_size[0], $this->pika_size[1]);

        $zufall = rand(1,99999999);

        #header("Content-Type: image/jpeg");
        imagejpeg($this->picture);
        imagedestroy($this->picture);

    }
}

$schild1 = new Schild();
$schild1->drawPicture();
?>

问题是您在 中声明变量__construct,但它们是局部变量。执行完成后__construct(),它会删除所有局部变量。您必须使用关键字将它们声明为 CLASS 变量$this,以便您的其他函数可以访问它们。

于 2012-07-16T17:40:55.777 回答