发布于2026-07-09 阅读(0)
扫一扫,手机访问
Ja va & PHP & Ja va(二)
上一回我们聊了PHP与Ja va结合的基础玩法,这次直接上一个实战例子——创建并使用你自己的Ja va类。整个过程其实比想象中简单,只要把几个关键点踩准,就能让PHP顺畅地调用Ja va方法。下面这张图先给个直观印象:

新建一个 phptest.ja va 文件,放到你的 ja va.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
* ja va phptest
* or
* ja va 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 < args.length; i++) {
String arg = args[i];
System.out.println(p.test(arg));
}
}
}
}
文件创建好后,在命令行用 ja vac phptest.ja va 编译一下,得到 phptest.class。然后创建一个PHP文件(比如 phptest.php),内容如下:
" . $myj->test("Hello World") . "";
$myj->foo = "A String Value";
echo "You ha ve set foo to " . $myj->foo . "
\n";
echo "My ja va method reports: " . $myj->whatisfoo() . "
\n";
?>
如果你跑的时候遇到 ja va.lang.ClassNotFoundException 错误,别慌——这通常意味着你的 phptest.class 文件没放在 ja va.class.path 所指定的目录里,检查一下路径即可。
这里有个容易踩的坑:Ja va是强类型语言,而PHP是弱类型。两者混用时,往Ja va变量赋值必须明确指定类型。比如 $myj->foo = (string) 12345678; 或者 $myj->foo = "12345678";,不能直接扔个数字进去,否则会报类型不匹配的错误。
这个例子虽然简单,但已经展示了最核心的路子:写一个带public方法的Ja va类,编译后通过PHP的Ja va扩展实例化并调用。掌握了这个模式,你就可以把任何自己写的Ja va类拿过来用,比如封装一些高性能计算、调用第三方Ja va库,甚至操作现有Ja va系统。思路打通之后,剩下的就是根据需求自由发挥了。
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
8