0

I am .net developer just started to work on PHP project with Laravel framework. In .net, we can create List frequently. What is the alternate way of doing same in PHP. After that, I want to pass that list as method parameter & accessing list items. I searched on google but can't find anything suitable. I know this may be very basic question from the view point of PHP developers. But I am still in confusion & can not proceed with my work.

eg in .net code, we create list object as -

public List<ReaderInfo> readerInfo = null;

To pass that list object in method -

InitReaderInfo(readerInfo);

Method definition is written as -

public void InitReaderInfo(List<ReaderInfo> reader)

Now, I want to convert the same in PHP. Any suggestion?

5
  • start study at php.net Commented Feb 13, 2017 at 9:33
  • use arrays. best way to achieve this. Commented Feb 13, 2017 at 9:34
  • If you're working with Laravel, then you want a Collection, not an array Commented Feb 13, 2017 at 9:38
  • @MarkBaker Thanks for your suggestion but i don't know how its working with my example. I will very thankful to you if you take some effort & explain with example . Commented Feb 13, 2017 at 9:45
  • 1
    The documentation is always a good place to start Commented Feb 13, 2017 at 9:52

1 Answer 1

1

PHP is not a strong type language. It also doesn't support generics or generic methods. That general means you cannot write this:

public List<ReaderInfo> readerInfo = null;

or this:

public void InitReaderInfo(List<ReaderInfo> reader)

There is no easy way to enforce type to list elements just by defining it. However, PHP supports argument types declaration so you can do this:

<?php

class Thing {
  private $name;
  public function __construct($name) {
    $this->name = $name;
  }
  public function __toString() {
    return $this->name;
  }
}

class Fruit extends Thing {}

class ThingList {
  private $list;
  public function __construct(Thing ...$list) {
    $this->list = $list;
  }
  public function __toString() {
    return array_reduce($this->list, function ($carry, $item) {
      return $carry . $item . "\n";
    }, '');
  }
}

function PrintThings(ThingList $list) {
  // ... do something to the thing list
  echo $list;
}

?>

in order to get better type-safety like this:

<?php

// declare a list of thing
$things = new ThingList(
  new Thing("apple"),
  new Fruit("orange")
);

PrintThings($things);

?>

If you're talking about Laravel specific solution, I suggest you to look at the jcrowe/type-safe-collection library, which you can do similar thing with a lot less labour.

Sign up to request clarification or add additional context in comments.

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.