如何在php中的类方法中返回数组长度?

时间:2015-09-08 14:12:52

标签: php arrays methods

我有一个数组:

$data = array("a", "b", "c");

我试图在类方法

中打印出这个数组的长度(3)
class MyString {
    public $myChars;
    public $length;

    function __construct($data) {
        $this->myChars = $data;
    }

    function length() {
        $length = count($this->myChars);
        return $length;
    }

来自:

$mystring = new MyString($data);

但这不起作用......

2 个答案:

答案 0 :(得分:3)

$mystring = new MyString($data);
print $mystring->length();

答案 1 :(得分:0)

对班级进行一些修改:

class MyString {
    public $myChars;
    public $length;

    public function __construct($data) {
       $this->myChars = $data;
    }

    public function length() {
       $this->length = count($this->myChars);
       return $this->$length;
    }
}

使用:

$mystring = new MyString($data);
print $mystring->length();