Reputation: 7880
I have some classes, and that classes are included in index.php
file , like :
<?php
include("./includes/user.class.php");
include("./includes/anotherclass.class.php");
?>
then I have :
$layout = new layout();
$layout->sampleMethod;
then in the body i have :
include("pages/samplePage.php");
then in that samplePage.php
i have to create new layout()
again to use class functions, is there a way to use $layout->method
in included file without create another object?
more code:
Layout class :
public function mkLayout()
{
include("pages/page.php");
}
public function getPageUrl()
{
echo "PAGE URL";
}
some of index.php :
<?php
require_once("includes/layout.class.php");
$layout = new layout();
$layout->mkLayout();
?>
some of samplePage.php
<?php
$layout->getPageUrl();
?>
the samplePage.php returns :
Fatal error: Call to a member function getPageUrl() on a non-object in
Upvotes: 1
Views: 252
Reputation: 6548
Going off what you have posted, if this is how your code looks:
<?php
include("./includes/user.class.php");
include("./includes/anotherclass.class.php");
$layout = new layout();
$layout->sampleMethod;
include("pages/samplePage.php");
?>
$layout
should already be declared in your pages/samplePage.php
. Try doing var_dump($layout)
in pages/samplePage.php
and you'll see that it is already defined.
Why not just have a layout member inside of your class?
Upvotes: 0
Reputation: 174947
If you are using $layout
in your included page, it should be working normally, assuming of course you declared $layout = new layout();
before you included samplePage.php
.
If it doesn't work for you, try var_dump()
ing it in your included page and see what you get there. Though it should be working as you are asking.
After digging a little I found that wherever the file is included it inherits the scope of the function/method that used it, so use
global $layout;
Before you try to use methods and it should be working fine.
When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward. However, all functions and classes defined in the included file have the global scope.
Useful links:
Upvotes: 1
Reputation: 4131
Maybe you are not really striving for object orientation in this example. Consider just using plain functions without classes.
Upvotes: 0
Reputation: 51
Nope, except you want to include the file that contains the previous instantiation of the layout class.
Upvotes: 1