当前位置: 首页 > 图文教程 > 网络编程 > PHP > php&java(二)

PHP
搜索和替换文件或目录的一个好类--很实用
树型结构列出指定目录里所有文件的PHP类
使用字符串函数输出整数化的PHP版本号
php录入页面中动态从数据库中提取数据的实现
定制404错误页面,并发信给管理员的程序
让你的PHP同时支持GIF、png、JPEG
一个颜色轮换的简单例子
二十行语句实现从Excel到mysql的转化
模仿OSO的论坛(四)
简体中文转换为繁体中文的PHP函数
繁体中文转换为简体中文的PHP函数
PHP安装攻略:常见问题解答(三)
基于数据库的在线人数,日访问量等统计
NO3第三帝国留言簿制作过程
一个没有MYSQL数据库支持的简易留言本的编写
PHP安装攻略:常见问题解答(二)
在windows iis5下安装php4.0+mysql之我见
PHP聊天室技术
利用PHP实现与ASP Banner组件相似的类
PHP安装攻略:常见问题解答(一)

PHP 中的 php&java(二)


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-13   浏览: 61 ::
收藏到网摘: n/a

例子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很好的调用它!