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

save blog article for offline html5 viewing

javascript html5 offline

There are lots of different ways to save state in html5, how do you give the user the ability to decide on which articles they want to save offline and read later?

Interfaces with static fields in java for sharing 'constants'


I'm looking at some open source Java projects to get into Java and notice a lot of them have some sort of 'constants' interface.

Free Source Control

visual-studio visual-studio-2010 version-control

Up until now, even though I do a lot of small home projects, I have never used any source control for my own projects. I am now almost at the point of deploying my first personal public website and

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.