php&java (2)

黄舟
Release: 2023-03-03 15:02:01
Original
1084 people have browsed it

Example 1: Create and use your own java classes
Creating your own JAVA classes is very easy. Create a new phptest.java file and place it in your java.class.path directory. The file content is as follows:

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));
}
}
}
}

After creating this file , we need to compile this file and use the javac phptest.java command on the DOS command line.

In order to test this JAVA class using PHP, we create a phptest.php file with the following content:


$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";

?>

If you get this warning message: java.lang.ClassNotFoundException error , it means that your phptest.class file is not in your java.class.path directory .
It should be noted that JAVA is a mandatory type language, but PHP is not. This can easily lead to errors when we integrate them, so when we pass variables to JAVA, we must correctly specify the type of the variable. Such as: $myj->foo = (string) 12345678; or $myj->foo = "12345678";

This is just a small example, you can create your own JAVA class and use PHP just fine ’ s calling it!

The above is the content of php&java (2). For more related articles, please pay attention to the PHP Chinese website (www.php.cn)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template