zl程序教程

您现在的位置是:首页 >  后端

当前栏目

php&java(二)

2023-06-13 09:13:44 时间
例子1:创建和使用你自己的JAVA类
创建你自己的JAVA类非常容易。新建一个phptest.java文件,将它放置在你的java.class.path目录下,文件内容如下:

publicclassphptest{
/**
*AsampleofaclassthatcanworkwithPHP
*NB:Thewholeclassmustbepublictowork,  
*andofcoursethemethodsyouwishtocall
*directly.
*
*AlsonotethatfromPHPthemainmethod
*willnotbecalled   
*/

publicStringfoo;

/**
*Takesastringandreturnstheresult
*oramsgsayingyourstringwasempty
*/
publicStringtest(Stringstr){    
if(str.equals("")){
      str="Yourstringwasempty.";    
}    
returnstr;   
}

/**
*whatisfoo()simplyreturnsthevalueofthevariablefoo.
*/   
publicStringwhatisfoo(){    
return"foois"+foo;   
}


/**
*Thisiscalledifphptestisrunfromthecommandlinewith
*somethinglike
*  javaphptest
*or
*  javaphptesthellothere
*/
publicstaticvoidmain(Stringargs[]){
phptestp=newphptest();

if(args.length==0){
Stringarg="";
System.out.println(p.test(arg));
}else{
for(inti=0;i<args.length;i++){
Stringarg=args[i];
System.out.println(p.test(arg));   
}
}
}
}

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

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

<?php

$myj=newJava("phptest");
echo"TestResultsare<b>".$myj->test("HelloWorld")."</b>";

$myj->foo="AStringValue";
echo"Youhavesetfooto<b>"   .$myj->foo."</b><br>n";
echo"Myjavamethodreports:<b>".$myj->whatisfoo()."</b><br>n";

?>

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

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