Using Arrays as parameters for functions

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
seem
Forum Newbie
Posts: 6
Joined: Fri Jun 28, 2002 9:48 am
Location: Munich, Germany

Using Arrays as parameters for functions

Post by seem »

Hello Everybody,

for my computer asset managment tool I've defined some container classes used transporting data from one class to another. For example there is a class host.

host.php look a little bit like the following:

Code: Select all

class host {
    getHostname() {
        return $this->hostname;
}
}
Now I want to create a function called createHostTable which requires an array of hosts and creates a table with all the host details. The functions are in different files. My approach was the following:

Code: Select all

function createHostTable ($hostsї]) {
    $elements = count ($hostsї]);
    for ($i = 0 ; $i < $elements) &#123;
        echo $hosts&#1111;$i]->getHostname;
        echo $hosts&#1111;$i]->getAlias;
    &#125;
&#125;
How can I use arrays as parameters for functions? Is there any way to pass something like a pointer to an existing array?

Thanks in advance

Andy
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

an array is a variable like any other (no type-safety at all).
So there's no way to check this at compile-time.

But your code would work without [] if the parameter is an object-array

Code: Select all

function createHostTable ($hosts) &#123; 
    $elements = count ($hosts); 
    for ($i = 0 ; $i < $elements;$i++) &#123; 
        echo $hosts&#1111;$i]->getHostname; 
        echo $hosts&#1111;$i]->getAlias; 
    &#125; 
&#125;
seem
Forum Newbie
Posts: 6
Joined: Fri Jun 28, 2002 9:48 am
Location: Munich, Germany

Post by seem »

volka wrote: for ($i = 0 ; $i < $elements;$i++) {
echo $hosts[$i]->getHostname;
echo $hosts[$i]->getAlias;
Thanks for your help, but there seems to be another problem.
The function drawHostTable is called correctly but the functions fo the array elements cannot be called. The follwing warnings appear:

Warning: Cannot use a scalar value as an array in /usr/local/httpd/htdocs/cat/php/rendering/pageFactory.php on line 54

Fatal error: Call to a member function on a non-object in /usr/local/httpd/htdocs/cat/php/rendering/pageFactory.php on line 54

if I do an echo $hosts in the drawHostTable function it says: Object which is similar to the host-object in the calling function
Post Reply