首页 编程教程正文

php&java(二)

piaodoo 编程教程 2020-02-02 13:48:01 858 0 php教程

例子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 < args.length; i++) {
String arg = args[i];
System.out.println(p.test(arg));   
}
}
}
}

创建这个文件后,我们要编译好这个文件,在DOS命令行使用javac phptest.java这个命令。

为了使用PHP测试这个JAVA类,我们创建一个phptest.php文件,内容如下:

<?php

$myj = new Java("phptest");
echo "Test Results are <b>" . $myj->test("Hello World") . "</b>";

$myj->foo = "A String Value";
echo "You have set foo to <b>"   . $myj->foo . "</b><br>n";
echo "My java method reports: <b>" . $myj->whatisfoo() . "</b><br>n";

?>

如果你得到这样的警告信息:java.lang.ClassNotFoundException error ,这就意味着你的phptest.class文件不在你的java.class.path目录下。
注意的是JAVA是一种强制类型语言,而PHP不是,这样我们在将它们融合时,容易导致错误,于是我们在向JAVA传递变量时,要正确指定好变量的类型。如:$myj->foo = (string) 12345678; or $myj->foo = "12345678";

这只是一个很小的例子,你可以创建你自己的JAVA类,并使用PHP很好的调用它!

版权声明:

本站所有资源均为站长或网友整理自互联网或站长购买自互联网,站长无法分辨资源版权出自何处,所以不承担任何版权以及其他问题带来的法律责任,如有侵权或者其他问题请联系站长删除!站长QQ754403226 谢谢。

有关影视版权:本站只供百度云网盘资源,版权均属于影片公司所有,请在下载后24小时删除,切勿用于商业用途。本站所有资源信息均从互联网搜索而来,本站不对显示的内容承担责任,如您认为本站页面信息侵犯了您的权益,请附上版权证明邮件告知【754403226@qq.com】,在收到邮件后72小时内删除。本文链接:http://www.piaodoo.com/3490.html

评论

搜索