1

I'm quite new with PHP. I'm having problems declaring an object as array for function parameter. In Java, I simply use public void methodName (List<Object> listVariableName){} for passing a list of many Objects.

I did some research in PHP and one of the answers suggested to put array in method parameter declaration like so function myFunction($a, array Object $obj){}

Currently, I have a class named Lesson

class Lesson implements JsonSerializable{
private $lessonId;
    private $lessonNo;
    private $lessonTitle;
    private $isLessonActive;
    private $isLessonRemoved;

    //getters and setter here....
}

Then I'm trying to declare a method called addTopicLesson

function addTopicLesson(Topic $topic, array Lesson $lesson){

}

But, I'm getting an error in array Lesson $lesson

There's 1 topic and MANY lessons. How can I go about implementing or defining the method signature?

I found this but I'd like to know if there's a better approach than to call itself.

I'd appreciate any suggestion.

Thank you.

1
  • 2
    You can't type hint array of Objects, either array or Object Commented Sep 22, 2018 at 13:40

2 Answers 2

1

List<T> is not an array. It's a list utilizing generic type mechanism.

There are no generics in PHP. You can only typehint an array but you cannot control what's inside it at the level of method declaration.

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

Comments

0
function addTopicLesson(Topic $topic,array $lessons)
{
  foreach($lessons as $lesson) 
  {
    addLesson($page);
  }
}

function addLesson(Lesson $lesson)
{
}

1 Comment

This way you can pass only one instance of Lesson object. It will refuse to take an array.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.