defining an initial variable in a new object in php

I am new to OOP so forgive me if my question is flawed.

I am writing a class to fetch and populate a data set, this will be performed within a loop, which will return a series of index id's by which I will populate the data of the object. Within the app, I will need to both do this in a loop, and individually. My question is when (inside or outside the loop) I initiate the class, how would I define the id for that particular object's item id, which will be used by the class's methods?

$object = New item($itemid);
// or
$object = New item->4;
// ?

I am not sure how to do this, or if this is even the proper way to handle this kind of logic.


I am writing this class under the assumption that my first object will be a collection of commonly used functions that currently only exist as such, so just trying to clean things up.


You need to initialize the class, and then set the item id.

$object = new item();
$object->item_id = 1;

The first way

class Item {
    private $id;

    public function __construct($id) {
        $this->id = $id;

$object = new Item($itemid);

Try to use private member variables where you can and set them with the constructor.

You can use constructors for that. Example:

  class person {
     public $name;
     public function __construct($persons_name) {           
       $this->name = $persons_name;            
    // ....   rest

Now, when you create the object with new keyword, pass the arguments.

  $user = new person('Ayesh K);

Otherwise you can explicitly set values for the class as well.

Need Your Help

Android - inflate views manually onto the Linear layout

android android-layout android-view

I have a layout comprising of many nested layouts some thing like shown below. But for one of the LinearLayout, (contentPanel in my case) i need to inflate around 10 views of different layout (some...

Drawing Diagonal Lines Across a Picture

python coordinates draw jython jes

I am trying to draw parallel lines diagonally from the top right corner to the bottom left corner of a picture. I want it to look like this (lovely paint pic)

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.