[英]Use external array inside class PHP
I have this function (in file functions.php) that returns me a list of the users in a database. 我有这个函数(在文件functions.php中),它返回一个数据库中的用户列表。
function db_listar_usuarios(){
$link = db_connect();
$query = "select * from usuarios" or die("Problemas en el select: " . mysqli_error($link));
$result = $link->query($query);
$myArray = array();
while($row = mysqli_fetch_assoc($result)) {
$myArray[$row['nombre']] = $row;
//print_r($myArray); // for debugging
}
return $myArray;
//print_r($myArray);
}
and i want to use it in a Class that is in another file (server.php) 我想在另一个文件中使用它(server.php)
<?php
include('functions.php');
class Server {
private $contacts = db_listar_usuarios(); //<-- this doesn't work =(
...
}
What can I do to make this code work? 我该怎么做才能使这段代码有效?
Thanks! 谢谢!
You can't call a function in that position. 你不能在那个位置调用一个函数。 When you declare class variables, they must be constants (see: http://www.php.net/manual/en/language.oop5.properties.php ).
声明类变量时,它们必须是常量(请参阅: http : //www.php.net/manual/en/language.oop5.properties.php )。
You need to use the constructor to do that. 您需要使用构造函数来执行此操作。
<?php
include('functions.php');
class Server {
private $contacts;
function __construct(){
$this->contacts = db_listar_usuarios();
}
}
PHP does not allow to set dynamic values in the property declaration. PHP不允许在属性声明中设置动态值。 You cannot call a function in that place.
你不能在那个地方调用一个函数。
You have to move that function call to the constructor, which is called automatically when an instance of that class is created: 您必须将该函数调用移动到构造函数,该构造函数在创建该类的实例时自动调用:
private $contacts;
public function __construct() {
$this->contacts = db_listar_usuarios();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.