php&java(二)

黄舟
发布: 2016-12-17 09:47:51
原创
1356人浏览过

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

 以上就是php&java(二)的内容,更多相关文章请关注PHP中文网(www.php.cn)!

PHP速学教程(入门到精通)
PHP速学教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号