使用面向对象编程在PHP中显示数组
我正在用PHP进行PHP和面向对象编程的实验。当我尝试运行以下使用面向对象编程在PHP中显示数组,php,arrays,oop,Php,Arrays,Oop,我正在用PHP进行PHP和面向对象编程的实验。当我尝试运行以下displayArray函数时,它根本不显示该行。有人知道我做错了什么吗 <?php class Student { var $name; var $arr; function Student() { $this->name = "bob"; $this->addnametostring("Hello there "); $this-&
displayArray
函数时,它根本不显示该行。有人知道我做错了什么吗
<?php
class Student
{
var $name;
var $arr;
function Student()
{
$this->name = "bob";
$this->addnametostring("Hello there ");
$this->arr = array();
for($i=0; $i<30; $i++) {
$arr[$i] = rand(0,100);
}
}
function addnametostring($s)
{
$s.= " " . $this->name;
echo "$s <br>";
}
function displayArray($amt)
{
foreach($this->arr as $key) {
//why is this not working
echo "<br>hello: ".$key;
}
}
更改此选项
for($i=0; $i<30; $i++){
$arr[$i] = rand(0,100);
}
for($i=0;$iname=“bob”;
$this->addnametostring(“你好”);
$this->arr=array();
对于($i=0;$iarr[$i]=rand(0100);
}
}
函数addnametostring($s){
$s.=“”.$this->name;
回声“$s
”;
}
函数displayArray($amt){
foreach($this->arr as$key){
//为什么这不起作用
回声“
你好:”.$key;
}
}
}
更改此选项
for($i=0; $i<30; $i++){
$arr[$i] = rand(0,100);
}
for($i=0;$iname=“bob”;
$this->addnametostring(“你好”);
$this->arr=array();
对于($i=0;$iarr[$i]=rand(0100);
}
}
函数addnametostring($s){
$s.=“”.$this->name;
回声“$s
”;
}
函数displayArray($amt){
foreach($this->arr as$key){
//为什么这不起作用
回声“
你好:”.$key;
}
}
}
php构造函数中的
如下所示
function __construct(){
//some code
}
所以您没有调用student函数。在php构造函数中如下所示
function __construct(){
//some code
}
因此,您没有调用student函数。您可以在第一次调用该类时使用a轻松分配数组
<?php
class Student
{
public $name;
public $arr;
function __construct()
{
$this->name = "bob";
$this->addnametostring("Hello there ");
$this->arr = array();
for($i=0; $i<30; $i++) {
$this -> arr[$i] = rand(0,100);
}
}
function addnametostring($s)
{
$s.= " " . $this->name;
echo "$s <br>";
}
function displayArray()
{
foreach($this->arr as $key) {
//why is this not working
echo "<br>hello: ".$key;
}
}
}
当您第一次调用该类时,可以使用来轻松分配数组
<?php
class Student
{
public $name;
public $arr;
function __construct()
{
$this->name = "bob";
$this->addnametostring("Hello there ");
$this->arr = array();
for($i=0; $i<30; $i++) {
$this -> arr[$i] = rand(0,100);
}
}
function addnametostring($s)
{
$s.= " " . $this->name;
echo "$s <br>";
}
function displayArray()
{
foreach($this->arr as $key) {
//why is this not working
echo "<br>hello: ".$key;
}
}
}
@kevinabelita请不要建议对op的代码进行实质性更改的编辑。格式化编辑是好的,但更改代码本身的编辑不是。删除了op的一个右大括号。右大括号很好,在编辑时,我可能错过了。谢谢提醒。脱离主题,但你的OOPS风格更像php-4样式的OOPS。我建议使用private而不是var,同时使用public/protected/private前缀方法,以便更好地理解php中的OOPS。@kevinabelita请不要建议对op的代码进行实质性更改的编辑。格式编辑是好的,但对代码本身进行更改的编辑不是。删除了op的一个右括号。Good在编辑时注意到右大括号,我可能没有注意到。谢谢你的提醒。不在主题范围内,但你的OOPS风格更像是php-4风格的OOPS。我建议使用private而不是var,同时使用public/protected/private前缀方法,以便更好地理解php中的OOPS。他的构造函数示例对php有效。php允许两者__构造函数和方法作为构造函数。只有命名空间类(>5.3.3)只将_构造函数视为构造函数。他的构造函数示例对PHP有效。PHP允许_构造函数和方法作为构造函数。只有命名空间类(>5.3.3)只将_构造函数视为构造函数。
$student = new Student;
echo "<br>";
$student-> displayArray();