簡體   English   中英

php OOP 示例 - 不知道出了什么問題

[英]php OOP example - can't figure out what's wrong

<?php

    class titleGenerator {
        public $names = array(
        'Best Beer',
        'Happy Burgers',
        'Alexs Nachos',
        'Big Sams Tacos'
        );
        public $i = rand(0, count($names)-1);

        public function sayTitle() {
            echo $names[$i];
        }
    }

    $titles = new titleGenerator;
    $titles->sayTitle();
?>

我正在嘗試學習 OOP 並制作了這種示例,但它不起作用,有人可以提供幫助嗎?

這一行:

public $i = rand(0, count($names)-1);

是錯的。 您不能在 php 中定義這樣的類屬性。 您必須在構造函數中設置它,同樣,從sayTitle方法中,您應該使用$this->names而不是$names

<?php

    class titleGenerator {
        public $names = array(
        'Best Beer',
        'Happy Burgers',
        'Alexs Nachos',
        'Big Sams Tacos'
        );
        public $i;

        public function __construct() {
             $this->i = rand(0, count($this->names)-1)
        }

        public function sayTitle() {
            echo $this->names[$this->i];
        }
    }

    $titles = new titleGenerator();
    $titles->sayTitle();
?>

請注意,現在您必須使用括號實例化對象才能調用構造函數方法:

$titles = new titleGenerator();

謝謝,它幫助了我,但為了讓代碼正確運行,我做了這個:`

class titleGenerator {
    public $names = array(
    'Best Beer',
    'Happy Burgers',
    'Alexs Nachos',
    'Big Sams Tacos'
    );

    public $i;

    public function __construct() {
        $this->i = rand(0, count($this->names)-1);
    }

    public function sayTitle() {
        echo $this->names[$this->i];
    }
}

$titles = new titleGenerator;
$titles->sayTitle();

?>`

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM