Jump to content

Object declared inside class


jsebast

Recommended Posts

Hey guys I'm trying to do the following but it gives me a parse error. I'm sure there's an easy way to do this but I can't find anything on it I'm using PHP Version 5.2.9:

 

<?php
  class foo
  {
    public function hello()
    {
      echo "Hello World this is Foo";
    }
  }
  class bar
  {
    private $fooClass = new foo();
    public function bar()
    {
      echo "Hello world this is bar";
      $fooClass->hello();
    }
  }
  
  $master = new bar();
  
?>

 

I get a parse error on the line that says:

private $fooClass = new foo();

 

I've seen and tried

$fooClass = new foo;

$fooClass = foo;

global $fooClass = new foo(); //or foo;

etc...

 

Suggestions? Thanks in advance.

Link to comment
https://forums.phpfreaks.com/topic/163551-object-declared-inside-class/
Share on other sites

You might have to move it to the constructor:

 

<?php
  class foo
  {
    public function hello()
    {
      echo "Hello World this is Foo";
    }
  }
  class bar
  {
    private $fooClass;
    public function __constructor()
    {
        $this->fooClass = new foo();
    }
    public function bar()
    {
      echo "Hello world this is bar";
      $this->fooClass->hello();
    }
  }
  
  $master = new bar();
  
?>

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.