Dan
Dan

Reputation: 1660

Putting require once in a php class

I'm just learning and playing about with php.

I'm trying to separate and clean up my code by putting parts of the php in another file and i'm using require_once to do it, but it doesn't work in a class, is there an alternative?

Here's my code;

<?php
  class test1 {
    require_once ( 'test.php' );
  }
?>

Upvotes: 1

Views: 4887

Answers (5)

ɹɐqʞɐ zoɹǝɟ
ɹɐqʞɐ zoɹǝɟ

Reputation: 4370

you can't simply put that in a class, you should use __construct() for this

OR

put that require_once() function outside of the class

AND A suggesion

Never try to include pages from the GET/POST requests, there is shell called "c99shell" which is used for hacking in such situations.

Upvotes: 2

STP38
STP38

Reputation: 331

<?php
  class test1 {
    require( 'test.php' );
  }
 test1();
?>

You can use require too. And call your class by adding "test1();" to your code.

Upvotes: 1

BastianW
BastianW

Reputation: 270

  class test1 {

    public function __construct(){
      require_once ( 'test.php' );
    }

  }

or

require_once ( 'test.php' );

class test1 {
 ...
}

or you put it in any function you need.

Upvotes: 1

h2ooooooo
h2ooooooo

Reputation: 39542

Put it outside the class (will be included when the class file is included):

<?php
    require_once('Bar.php');

    class Foo {
        //Do whatever
    }
?>

or use a __construct (will be included when the class is created the first time (new Foo())):

<?php
    class Foo {
        public function __construct() {
            require_once('Bar.php');
        }

        //Do whatever
    }
?>

Upvotes: 1

silly
silly

Reputation: 7887

<?php

  require_once ( 'test.php' );

  class test1 {
  }
?>

or

<?php
  class test1 {
     function requireOnce() {
         require_once ( 'test.php' );
     }
  }
?>

Upvotes: 1

Related Questions