php&java(二)
2024-05-04 23:00:35
供稿:網友
菜鳥學堂:
例子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很好的調用它!