php oop中的数组

问题描述 投票:0回答:3

我有数组,我在其中放置数据取决于URL。但是有问题,我无法像简单的php中那样打印此数组:

$ array = [“ hi”,“ name”]; echo $ array [1];

我将显示的代码有什么问题以及如何打印数组

产品编号:

<?php

class Translate {

    public $transl = [];

    public function getTransl($transl = []) {
        if (( isset($_GET['lang']))) {
    if ($_GET['lang'] == "en") {
        $this->transl = ['word1', 'word2'];
        }
        if ($_GET['lang'] == "ru") {
            $this->transl = ['word3', 'word4'];
            }
}
    }

}

$test = new Translate();
$test->getTransl([0]);

?>
php oop
3个回答
1
投票

不知道,为什么在需要特定索引时为什么要在方法参数中使用$transl = [],您只需要传递所需的键即可。

示例:

<?
class Translate {

    public $transl = 0;

    public function getTransl($transl = '') {
      if (( isset($_GET['lang']))) {
        if ($_GET['lang'] == "en") {
          $this->transl = ['word1', 'word2'];
        }
        if ($_GET['lang'] == "ru") {
            $this->transl = ['word3', 'word4'];
        }
      }
      return $this->transl[$transl];
    }
}

$test = new Translate();
echo $test->getTransl(0); // this will print `word1` if $_GET['lang'] equal to `en`
?>

在您的代码中,您没有在方法中使用echoreturn来获取结果。


0
投票

首先,您不将索引作为参数传递。您将其用作索引。正确的语法为:

$test->getTransl()[0];

假设$ test-> getTransl()返回一个数组。但事实并非如此。它不返回任何东西。它只是设置类属性$ transl。因此,您必须在两行中执行此操作:

$test->getTransl(); // This sets the attribute
$test->transl[0]; // This uses the attribute

但是,这与方法所暗示的相反。该方法暗示它返回transl属性。因此,您应该使用以下函数将其返回:

return this->transl;

然后,您可以使用:

$test->getTransl()[0];

当然,这不会打印任何内容。您需要在前面加上echo或print:

echo $test->getTransl()[0];

0
投票

我认为您只需要返回输出。

假设您的服务器上有一个名为test.php的文件

class Translate {

    public $transl = [];

    public function getTransl($transl = []) {
        if (( isset($_GET['lang']))) {
            if ($_GET['lang'] == "en") {
                $this->transl = ['word1', 'word2'];
            }
            if ($_GET['lang'] == "ru") {
                $this->transl = ['word3', 'word4'];
            }
        }
        return $this->transl;
    }

}

$test = new Translate();
$output=$test->getTransl([0]);
echo "<pre>";
    print_r($output);
echo "</pre>";

在浏览器中运行http://server/ {{enterfolderhere}} / test.php?lang = en将提供

Array
(
    [0] => word1
    [1] => word2
)

运行http://server/ {{enterfolderhere}} / test.php?lang = ru在您的浏览器中会显示

Array
(
    [0] => word3
    [1] => word4
)
© www.soinside.com 2019 - 2024. All rights reserved.