Jump to content

[SOLVED] Possible to create a class object in a class?


suntin

Recommended Posts

class myClass{
var $taxRate  = 0.75;
var $vouchers = Array();
var $charges  = Array();
var $items = new booking();

 

results in:

 

Parse error: syntax error, unexpected T_NEW in ...

 

The class I want to construct deals with some complex queries and it seems a shame to duplicate the code in a child class.

(I am however still learning)

 

I'm sure it's possible but that I'm using the wrong syntax.

Why don't you use a main 'class'?

 

include('myClass1.php') // which contains MyClass1;
include('myClass2.php') // which contains MyClass2;

$myClass1 = new myClass1();
$myClass2 = new myClass2();

$taxRate = myClass1->$taxRate;
$newVar = myClass2->$var2;

 

This way use can your variables and functions of both classes together.

class myClass{
  var $taxRate;
  var $vouchers;
  var $charges;
  var $items;

  function myClass()
  {
    $this->taxRate = 0.75;
    $this->vouchers = Array();
    $this->charges = Array();
    $this->items = new booking();
  }

 

try that

 

monk.e.boy

was just hoping to keep it simple, technically all the classes are included by the site's template anyway.

 

booking() returns stuff I don't need but it makes more sense to use its getBooking() function than to have almost identical SQL in separate files. would be harder to maintain otherwise.

 

I'll have a play with this but it seems odd php doesn't like the code as it is.

 

monk.e.boy was posting while I wrote this, I remember reading that you shouldn't assign values to properties of the main class but use the constructor, because ints/strings and arrays don't error I assumed this information wasn't true.

 

I guess it's something that would be good to have in PhP but if it's not there I can work with that.

 

 

[EDIT] I am not gonna mark this as solved for a few hours in case someone knows more about the issue, but I reckon monk.e.boy hit the nail.

The error you got was a syntax error. So I changed the syntax you posted so it had no errors, so technically the problem is solved  ;D ;D ;) ;)

 

PHP is a bit of a monkey language. The problem you had should not be a problem. And it isn't in a real language. It's PHP that is at fault.

 

monk.e.boy

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.