2013-05-26 6 views
0

내가, 하나 개의 기능 테스트 클래스를 가지고 예를 들어, 내가 포함 된 페이지와이 클래스의 기능을 사용할 수 있지만 내가 포함 된 페이지의 기능에 대한이 기능을 사용하지 못할 것을 포함 후 :PHP 사용 클래스 기능

testClass.php : 내가 문제

text.php에게 해달라고 사용하여이 클래스 : 0 클래스를 포함

class test 
{ 
    public function alert_test($message) 
    { 
     return $message; 
    } 
} 
<?php 
include 'testClass.php'; 
$t= new test; 
echo alert_test('HELLO WORLD'); 
?> 

하지만 난이 방법 alert_test 기능을 사용하지 못할 :

<?php 
include 'testClass.php'; 
$t= new test; 
function test1 ($message) 
{ 
     echo alert_test('HELLO WORLD'); 
/* 
     OR 

     echo $t->alert_test('HELLO WORLD'); 
*/ 
} 
?> 

난 하위 기능

echo $t->alert_test('HELLO WORLD');에 대한

답변

0

당신은 당신의 기능에 인스턴스 ($t)를 통과해야 예 :

대안 (더 나은 IMHO) 당신도 인스턴스화 할 필요가 없습니다 있도록, static로 함수를 선언 할 수로
<?php 

class test 
{ 
    public function alert_test($message) 
    { 
     return $message; 
    } 
} 

$t = new test; 

function test1 ($message, $t) 
{ 
    echo $t->alert_test('HELLO WORLD'); 
} 

test 클래스, 즉 :

class Message { 
    static function alert($message) { 
    echo $message; 
    } 
} 

function test_alert($msg) { 
    Message::alert($msg); 
} 

test_alert('hello world'); 
+0

고마워,하지만 클래스 파일에 alert_test 함수를 사용하는 걸 좋아하지 않아. –

1

무엇에 테스트 클래스를 사용하려면를? PHP에게 함수를 찾을 곳을 알려줘야합니다.이 경우에는 테스트 클래스의 인스턴스 인 $ t에 있습니다.

<?php 
include 'testClass.php'; 
function test1 ($message) 
{ 
    $t = new test; 
    echo $t->alert_test('HELLO WORLD'); 
} 
?> 
+1

'객체가 아닌 객체에서 alert_test() 멤버 함수 호출 ... ' –

+0

전체 코드가 포함되도록 내 대답이 업데이트되었습니다. – Silox

0

alert_test()test 클래스의 인스턴스 기능이 있기 때문에 당신은 심지어 첫 번째 예제에서 "문제가있다"한다. 함수 인수로 전달할 : [당신이 test1로] 전역 개체에 의존해서는 안

$t -> alert_test(); 

그러나 지역 기능 :

$instance -> method($params); 

그래서 :

당신은 인스턴스 메서드를 호출해야 필요한 경우.

0

당신이 사용할 수있는 폐쇄 :

$t = new test; 
function test1($message) use ($t) { 
    $t->test_alert($message); 
}