Dave Kiss
Dave Kiss

Reputation: 10485

What is the Equivalent of C#'s "List <String>" in PHP?

I'm working with an API and it is asking me to provide a List <String> value. I'm writing PHP and can only seem to find this type in C#.

Is it an array? A comma-separated string?

Upvotes: 19

Views: 11391

Answers (6)

Piotr F.
Piotr F.

Reputation: 11

This thread is old, but I think that code may helps:

class ClientList implements IteratorAggregate {

   protected $data;

   public function __construct(Client ...$data){
      $this->data = $data;
   }

   public function getIterator(): Traversable {
      return new ArrayIterator($this->data);
   }

}

class Client {

}


$clients[] = new Client();
$clients[] = new Client();

$clientList = new ClientList(...$clients);

foreach($clientList as $client){
   var_dump($client);
}

Now when you insert a string, number or something that isn't a Client instance that you would get error, and thanks to IteratorAggregate you can iterate on ClientList object.

Upvotes: 1

Kakashi
Kakashi

Reputation: 2195

PHP does not have the concept of generic types.

You can use array():

PHP

 $arr = array();  
 $arr[0] = 'foo';

equivalent in C#

List<string> arr = new List<string>(); 
arr.Add("foo"); 

Upvotes: 12

Dmitri Snytkine
Dmitri Snytkine

Reputation: 1126

If you are calling SOAP then you should just use php's SoapClient class, it does a good job at converting types it sees in wsdl into native php structures, usually into arrays or often into instances of stdClass objects, which is php's type of class that can store any value as property. Also you can do a more interesting things like tell php's SoapClient to map return types to your own php's objects.

See https://www.php.net/SoapClient and also see definition of constructor https://www.php.net/manual/en/soapclient.soapclient.php and one of the options called 'classmap' explains how you can map returned types to your own classes. There is also a 'typemap' option to map return types to your own types

Upvotes: 1

Eugene Manuilov
Eugene Manuilov

Reputation: 4361

Is it an array?

Yes, it is

A comma-separated string?

No, it isn't

Upvotes: 2

MRM
MRM

Reputation: 435

PHP is untyped, so you can use your array for all type of variable,use this code:

$arr=array();

Upvotes: 1

Maxime Pacary
Maxime Pacary

Reputation: 23061

I guess that you can use a simple array:

$list = array('string1', 'string2', 'string3');

or

$list = array();
$list[] = 'string1';
$list[] = 'string2';
$list[] = 'string3';

etc.

Check http://www.php.net/manual/en/language.types.array.php for details.

Upvotes: 8

Related Questions