>  기사  >  백엔드 개발  >  php与java二_PHP教程

php与java二_PHP教程

WBOY
WBOY원래의
2016-07-13 17:30:34843검색

例子1:创建和使用你自己的JAVA类
创建你自己的JAVA类非常容易。新建一个phptest.java文件,将它放置在你的java.class.path目录下,文件内容如下:
public class phptest{
/**
* A sample of a class that can work with PHP
* NB: The whole class must be public to work,
* and of course the methods you wish to call
* directly.
*
* Also note that from PHP the main method
* will not be called
*/
public String foo;
/**
* Takes a string and returns the result
* or a msg saying your string was empty
*/
public String test(String str) {
if(str.equals("")) {
str = "Your string was empty. ";
}
return str;
}
/**
* whatisfoo() simply returns the value of the variable foo.
*/
public String whatisfoo() {
return "foo is " + foo;
}

/**
* This is called if phptest is run from the command line with
* something like
* java phptest
* or


* java phptest hello there
*/
public static void main(String args[]) {
phptest p = new phptest();
if(args.length == 0) {
String arg = "";
System.out.println(p.test(arg));
}else{
for (int i=0; i String arg = args[i];
System.out.println(p.test(arg));
}
}
}
}
创建这个文件后,我们要编译好这个文件,在DOS命令行使用javac phptest.java这个命令。
为了使用PHP测试这个JAVA类,我们创建一个phptest.php文件,内容如下:
$myj = new Java("phptest");
echo "Test Results are " . $myj->test("Hello World") . "";
$myj->foo = "A String Value";
echo "You have set foo to " . $myj->foo . "
n";
echo "My java method reports: " . $myj->whatisfoo() . "
n";
?>
如果你得到这样的警告信息:java.lang.ClassNotFoundException error ,这就意味着你的phptest.class文件不在你的java.class.path目录下。
注意的是JAVA是一种强制类型语言,而PHP不是,这样我们在将它们融合时,容易导致错误,于是我们在向JAVA传递变量时,要正确指定好变量的类型。如:$myj->foo = (string) 12345678; or $myj->foo = "12345678";
这只是一个很小的例子,你可以创建你自己的JAVA类,并使用PHP很好的调用它!

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/509171.htmlTechArticle例子1:创建和使用你自己的JAVA类 创建你自己的JAVA类非常容易。新建一个phptest.java文件,将它放置在你的java.class.path目录下,文件内容如下...
성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.