php OOP示例 - 无法弄清楚出了什么问题

时间:2015-09-02 21:29:05

标签: php oop

Integer.parseInt(lineVector[i])

我正在尝试学习OOP并制作了这样的例子,但它不起作用,有人可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

这一行:

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

答案 1 :(得分:0)

谢谢,它帮助了我,但是为了使代码运行正确,我做了这个: `

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

&GT;`