Reputation: 1660
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
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
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
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
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
Reputation: 7887
<?php
require_once ( 'test.php' );
class test1 {
}
?>
or
<?php
class test1 {
function requireOnce() {
require_once ( 'test.php' );
}
}
?>
Upvotes: 1