Accessing array element within public function in

2019-08-04 08:35发布

问题:

Trying to figure out how to work with array elements with a public function inside a PHP class. Have reviewed already similar questions, but without being able to resolve the issue. Below is what I have so far.

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

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

$obj = new myClass;

echo $obj->printOutput();

回答1:

You can also use defined values. other wise good to pass in constructor

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

here is running snippet: https://ideone.com/miOQJB



回答2:

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


标签: php arrays class