简体   繁体   English

PHP 在 function 内填充数组

[英]PHP populate array inside a function

i have a small problem with my php code.我的 php 代码有一个小问题。

i've created a class for Clients, to return me a list with all clients.我已经为客户创建了一个 class,向我返回一个包含所有客户的列表。 The problem is when i call the function from outsite, it dont show me the clietsList.问题是当我从外部调用 function 时,它没有显示 clietsList。

<?php 

$returnData = array();

class Clients
{
     public function readAll(){
        $query = "SELECT * FROM clients";
        $result = $this->con->query($query);
        if ($result->num_rows > 0){
            while ($row = $result->fetch_assoc()){
                $returnData['clientsList'][] = $row;
            }
            return $returnData;
        }
        else{
            echo "No found records";
        }
    }
}


if ($auth->isAuth()){
    $returnData['message'] = "you are loggedin, so is ok";
    $clientsObj = new Clients();
    $clientsObj->readAll();
}

echo json_encode($returnData);
?>

and the result is like that, but without clietslist结果就是这样,但没有 clietslist

{
  "message": "you are loggedin, so is ok"
}

Where im doing wrong?我在哪里做错了? Thanks for your answer.感谢您的回答。 i want to learn php, im begginer.我想学习 php,我是初学者。 thanks in advance.提前致谢。

You need to get return value of function in a variable:您需要在变量中获取 function 的返回值:

$returnData['message'] = "you are loggedin, so is ok";
$clientsObj = new Clients();
$returnData['clients'] =    $clientsObj->readAll();

$returnData on you first line will not be same as $returnData in your function.第一行的$returnData returnData 与 function 中的$returnData returnData 不同。 $returnData in readAll function will be a new variable. readAll function 中的$returnData returnData 将是一个新变量。

I suggest you to read about variable scope in php.我建议您阅读 php 中的变量 scope。 https://www.php.net/manual/en/language.variables.scope.php https://www.php.net/manual/en/language.variables.scope.php

Now, You will need to store returned value from function in a variable like this现在,您需要将 function 的返回值存储在这样的变量中

$returnData['message'] = "you are loggedin, so is ok";
$clientsObj = new Clients();
$clientListArray =  $clientsObj->readAll(); //store returned value in a variable
$returnData['clientsList'] = $clientListArray['clientsList'];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM