View Full Version : object oriented php problem

06-08-2007, 03:55 PM

i have the followin class defined

class B

public a = 2;

function ab() {}


now when i try to access the variable a from outside the class i get the error

obj1 = new B();

Can anyone tell me whats the problem

06-08-2007, 04:00 PM
What is the error you're getting? I'll bet it has something to with the following:

public a = 2;

...should be this:
public $a = 2;

06-08-2007, 04:32 PM
I have declared public $a = 2

the error is

Undefined property B::a in line ......

06-08-2007, 04:33 PM
Looks kinda like the java method without the datatypes
Definitly caused by the lack of $, it is attempting to find the value of 'a' stored as a constant (which does not exist). Error_reporting(E_ALL) when developing can show lots of troubles.

On a side note, since you appear to be using a php 5 oop engine, you may want to create your variables in a private scope. This of course completely depends on what the value represents, but a public attribute will allow direct manipulation - which of course bypasses any type of error checking you perform. This may not be an optimal way to operate the code, especially if used for distribution. Instead, use getters and mutators to alter the value of the code.

Hope that helps you out!

I see you posted above me.
You do have php 5 installed correct?

06-08-2007, 04:54 PM
Thnaks dude
Found the problem ,the file i was saving was placed somewhere else and i was editing the wrong file(LOL)

I think u r right Fou-LU . There should be getters and setters.

One more thing i want to ask

How we access variables which are defined inside the function of a class

eg class B

function { var $a;}


now how we can access {a} outside class

06-08-2007, 05:01 PM
There are two ways to obtain data within a class function:

use the method statically and return the result:

public static function userFunc($a = 0)
return $a++;
// Called as:

Assign the given value to an attribute and use a getter for the value: (Skipping getters and setters for simplicity sake)

public $a;

public function userFunc($a = 0)
$this->a = $a++;

// Called as:
$obj = new CLASS();

Hope that helps you out!

For the example you gave, the static method with a returned result is probably the best solution.

06-08-2007, 05:14 PM
Thanks very much dude

As clear as Good Object Oriented Book........

06-08-2007, 09:21 PM
The increments are not effective in the examples.

06-09-2007, 01:15 AM
The increments are not effective in the examples.

Sry, my bad on that one:


Preincrement it and it will work :P