帝国软件
  设为首页 加入收藏 关于我们
 
解密帝国网站管理系统
栏 目:
 
您的位置:首页 > 技术文档 > PHP编程
php 与 java(二)
作者:井中月 发布时间:2005-03-11 来源:
例子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 " . $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很好的调用它!
  
评论】【加入收藏夹】【 】【打印】【关闭
※ 相关链接
无相关信息

   栏目导行
  PHP编程
  ASP编程
  ASP.NET编程
  JAVA编程
   站点最新
·致合作伙伴的欢迎信
·媒体报道
·帝国软件合作伙伴计划协议
·DiscuzX2.5会员整合通行证发布
·帝国CMS 7.0版本功能建议收集
·帝国网站管理系统2012年授权购买说
·PHPWind8.7会员整合通行证发布
·[官方插件]帝国CMS-访问统计插件
·[官方插件]帝国CMS-sitemap插件
·[官方插件]帝国CMS内容页评论AJAX分
   类别最新
·Windows下集成安装Apache,PHP,MYSQ
·Mysql注入:SQL Injection with MyS
·PHP 的来龙去脉
·PHP 的功能概述
·PHP与其它CGI的比较
·PHP 的编译配置详细选项
·php.ini 配置详细选项
·如何写作PHP程序
·Hello,World
·嵌入方法
 
关于帝国 | 广告服务 | 联系我们 | 程序开发 | 网站地图 | 留言板 帝国网站管理系统