0

Is this possible?

class Foo {
  public function bar() {
   return true;
  }
}

class Foo2 {
  $fooey = new Foo;

  public function bar2() {
    if ( $fooey->bar ) {
        return 'bar is true';  
    }
  }
}

I realize the above would not work because I need to get $fooey inside the scope of bar2. How would I do this?

Thanks in advance.

2 Answers2

2

You can't create an object in a class outside of the functions, so use __construct as that will run first when the object is created.

<?php

class Foo {
  public function bar() {
   return true;
  }
}

class Foo2 {
  private $fooey = null

public __construct() {
    $this->fooey = new Foo();
}

  public function bar2() {
    if ( $this->fooey->bar ) {
        return 'bar is true';  
    }
  }
}

?>
Script47
  • 14,230
  • 4
  • 45
  • 66
0

What you have is not valid PHP syntax. I believe you're looking for something like this:

class Foo {
  public function bar() {
   return true;
  }
}

class Foo2 {
    private $fooey;
    public function __construct() {
      $this->fooey = new Foo;
    }

  public function bar2() {
    if ( $this->fooey->bar() ) {
        return 'bar is true';  
    }
  }
}

$obj = new Foo2;
$obj->bar2(); // 'bar is true' will be printed
  1. You need to initialize things in the constructor (or pass it in as a variable).

  2. You need to use $this to refer to own properties.

Anonymous
  • 11,740
  • 3
  • 40
  • 50