Reputation:
i have test class with one function , after including that i can use this class function with included pages but i cant use this function on included page's functions, for example:
testClass.php:
class test
{
public function alert_test( $message )
{
return $message;
}
}
including class: in this using class i dont have problem
text.php:
<?php
include 'testClass.php';
$t= new test;
echo alert_test('HELLO WORLD');
?>
but i cant use alert_test function with this method:
<?php
include 'testClass.php';
$t= new test;
function test1 ( $message )
{
echo alert_test('HELLO WORLD');
/*
OR
echo $t->alert_test('HELLO WORLD');
*/
}
?>
i want to use test class in sub-functions
Upvotes: 0
Views: 1512
Reputation: 21272
You should pass the instance ($t
) to your function, i.e:
<?php
class test
{
public function alert_test( $message )
{
return $message;
}
}
$t = new test;
function test1 ( $message, $t )
{
echo $t->alert_test('HELLO WORLD');
}
As an alternative (better IMHO) you could declare your function as static
, so that you don't even need to instantiate the test
class, i.e:
class Message {
static function alert($message) {
echo $message;
}
}
function test_alert($msg) {
Message::alert($msg);
}
test_alert('hello world');
Upvotes: 0
Reputation: 414
You can use closures:
$t = new test;
function test1($message) use ($t) {
$t->test_alert($message);
}
Upvotes: 0
Reputation: 1837
What about echo $t->alert_test('HELLO WORLD');
? You have to 'tell' PHP where he has to find that function, in this case in $t which is an instance of the test class.
<?php
include 'testClass.php';
function test1 ( $message )
{
$t = new test;
echo $t->alert_test('HELLO WORLD');
}
?>
Upvotes: 1
Reputation: 22817
You should "have problem" even in your first example, because alert_test()
is an instance function of your test
class.
You have to invoke instance methods as:
$instance -> method( $params );
So:
$t -> alert_test();
But local functions [as your test1
] should not rely on global objects: pass them as a function argument, if you need.
Upvotes: 0