PHP怎么调用其他类的方法

PHP怎么调用其他类的方法,第1张

在Java的调用方法是import,而在PHP中没有import这个函数,一般PHP中调用其他类是用到require(),具体PHP调用其他类的方法如下:

1、首先应该先有一个文件名为tool.php的文件,在文件中声明一个类。

2、然后需要有另一个文件名为main.php的文件,在文件中调用上面的类。方法如下。

扩展资料:

类是变量与作用于这些变量的函数的集合。使用下面的语法定义一个类:

<?php

class Cart { var $items// 购物车中的物品

// 将 $num 个 $artnr 物品加入购物车

function add_item($artnr, $num) {

$this->items[$artnr] += $num

} // 将 $num 个 $artnr 物品从购物车中取出

function remove_item($artnr, $num) {

if ($this->items[$artnr] >$num) {

$this->items[$artnr] -= $numreturn true

} elseif

($this->items[$artnr] == $num) {

unset($this->items[$artnr])return true

} else {

return false}

}

} ?>

上面的例子定义了一个 Cart 类,这个类由购物车中的商品构成的数组和两个用于从购物车中添加和删除商品的函数组成。

参考资料来源:百度百科-php类

file1.php类如下:

class A{

...

}

file2.php调用file2.php中的类如下:

include "file1.php"

class B{

$C = new A()

.....

}

你的这种定义方法是错误的,在类定义中不能直接包含文件或实例化对象,只能对类中属性进行定义;

请参考天南(46926125)写的DEMO:

###PHP DEMO CODE###

<?php

class b{

//include('a1.php') //类中不能直接包含文件,应在类定义外部或者类中的方法中包含文件

//$c=new a() //类定义中不能直接实例化另一个类,应该在类中的方法中实例化另一个类

function run(){

include('./a1.php')

return new a()

}

function d(){

$c=$this->run()

$c->ec()

}

}

$Obj=new b

$Obj->d()

?>


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/tougao/11543124.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-16
下一篇 2023-05-16

发表评论

登录后才能评论

评论列表(0条)

保存