在php类中访问公共函数中的数组元素

时间:2017-10-08 15:07:27

标签: php arrays class

试图弄清楚如何使用PHP类中的公共函数处理数组元素。已经审核过类似的问题,但无法解决问题。以下是我到目前为止的情况。

string headLine = "Example";
Console.WriteLine(headLine);
char c = '=';
for (int i=0; i < headLine.Length; i++) //from 0 to length-1 gives the full length
{
    Console.Write(c);
}

2 个答案:

答案 0 :(得分:1)

您还可以使用定义的值。传递构造函数的其他明智之处

<?php

class myClass
{
public $inputNumber = 27;
public $inputArray = array(1, 2, 4);
public $outputArray = array();

function __construct() {
   $this->outputArray= array($this->inputArray[0]*$this->inputNumber, 
                             $this->inputArray[1]*$this->inputNumber, 
                             $this->inputArray[2]*$this->inputNumber
                             );
}
public function printOutput()
{
    $output = "1st value is " . $this->outputArray[0] . "<br>";
    $output .= "2nd value is " . $this->outputArray[1] . "<br>";
    $output .= "3rd value is " . $this->outputArray[2] . "<br>";
    return $output;
 }
}

$obj = new myClass;
echo $obj->printOutput();

此处正在运行代码段:https://ideone.com/miOQJB

答案 1 :(得分:0)

class myClass
{
    public $inputNumber = (int) 27;
    public $inputArray = array();
    public $outputArray = array();

   function __construct($inputNumber = 27, $inputArray = array(1,2,4)) {
       $this->inputNumber = (int) $inputNumber;
       $this->inputArray = (array) $inputArray;
       $this->outputArray= array($this->inputArray[0]*$this->inputNumber, $this->inputArray[1]*$this->inputNumber, $this->inputArray[2]*$this->inputNumber);
    }

    public function printOutput()
    {
        return "1st value is " . $this->outputArray[0] . "<br>"
        . "2nd value is " . $this->outputArray[1] . "<br>"
        . "3rd value is " . $this->outputArray[2] . "<br>";
    }
}

$obj = new myClass;

echo $obj->printOutput();