当前位置:编程学习 > JAVA >>

php&java(二)

例子1:创建和使用你自己的JAVA类
创建你自己的JAVA类非常容易。新建一个php(做为现在的主流开发语言)test.java文件,将它放置在你的java.class.path目录下,文件内容如下:

public class php(做为现在的主流开发语言)test{
/**
* 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 php(做为现在的主流开发语言)test is run from the command line with
* something like
*  java php(做为现在的主流开发语言)test
* or
*  java php(做为现在的主流开发语言)test hello there
*/
public static void main(String args[]) {
php(做为现在的主流开发语言)test p = new php(做为现在的主流开发语言)test();
     
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 php(做为现在的主流开发语言)test.java这个命令。

为了使用php(做为现在的主流开发语言)测试这个JAVA类,我们创建一个php(做为现在的主流开发语言)test.php(做为现在的主流开发语言)文件,内容如下:

<?php(做为现在的主流开发语言)

$myj = new Java("php(做为现在的主流开发语言)test");
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 ,这就意味着你的php(做为现在的主流开发语言)test.class文件不在你的java.class.path目录下。
注意的是JAVA是一种强制类型语言,而php(做为现在的主流开发语言)不是,这样我们在将它们融合时,容易导致错误,于是我们在向JAVA传递变量时,要正确指定好变量的类型。如:$myj->foo = (string) 12345678; or $myj->foo = "12345678";

这只是一个很小的例子,你可以创建你自己的JAVA类,并使用php(做为现在的主流开发语言)很好的调用它!
补充:Web开发 , php ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,