0

I have this function (in file functions.php) that returns me a list of the users in a database.

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)

<?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!

2 Answers 2

1

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).

You need to use the constructor to do that.

<?php
include('functions.php');

class Server {    
    private $contacts;

    function __construct(){
        $this->contacts = db_listar_usuarios();
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Perfect! Excellent response!
Glad I could help! :-D
1

PHP does not allow to set dynamic values in the property declaration. 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();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.