【背景】
已经有了:
里面有一堆的函数代码。
现在想要封装成类,并且在别的php中调用该类的功能。
【折腾过程】
1.搜:
php中如何写类 如何使用类
参考:
一个php文件中怎么写一个类调用另外一个Php文件的类_百度知道
1 2 3 4 5 6 7 8 9 10 11 | file1.php类如下: class A{ ... } file2.php调用file2.php中的类如下: include "file1.php" ; class B{ $C = new A(); ..... } |
lessons/如何写好一个PHP的类 at master · monkee/lessons
PHP 类的变量与成员,及其继承、访问与重写要注意的问题 – ecalf – 博客园
1 2 3 4 5 6 7 | class Myclass{ public $prop = 123; } $obj = new Myclass(); |
找到官网的:
里面解释的比较清楚。
2.自己去试试。
期间又涉及到:
3.然后自己基本上实现了:
在一个PHP文件中定义类:
crifanLib.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | <?php /* [Filename] crifanLib.php [Function] crifan's php lib, implement common functions [Author] Crifan Li [Contact] [Note] 1.online see code: [TODO] [History] [v2015-07-27] 1.add logInit, logWrite [v1.0] 1.initial version, need clean up later */ class crifanLib { private $logFile ; private $logFp ; /* Init log file */ function logInit( $inputLogFile = null){ ... } /* Write log info to file */ function logWrite( $logContent ){ ... } } ?> |
在另外一个PHP文件中引用该类:
wx_access_token.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <?php /* File: wx_access_token.php Author: Crifan Li Version: 2015-07-27 Contact: https://www.crifan.com/about/me/ Function: Wechat get access token */ // https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET include_once "crifanLib.php" ; //test log $crifanLib = new crifanLib(); $crifanLib ->logInit( "/var/www/120.26.121.239/public_html/php/access_token/logTest.log" ); $crifanLib ->logWrite( "This is crifanLib log test message." ); $crifanLib ->logDeinit(); ?> |
4.再去搞懂:
如何实现php的类的初始化
搜:
php 类的初始化
参考:
5.期间又遇到:
然后研究如何写构造函数:
PHP 构造方法 __construct()_PHP基础教程
最后才加上了构造函数:
1 2 3 4 5 6 7 8 9 10 11 | class crifanLib { private $logFile ; function __construct() { $this ->logInit(); } function logInit( $inputLogFile = null) { ... } } |
别处直接调用即可:
1 2 3 4 | include_once "crifanLib.php" ; //test log $crifanLib = new crifanLib(); $crifanLib ->logWrite( "This is crifanLib log test message not pass log file name" ); |
【总结】
其实PHP中的定义类再引用类,和其他面向对象的语言的写法基本一致。
稍微特殊点的是:
(1)PHP v5中,构造函数统一命名为__construct -> 析构函数统一为__destruct。
(2)一定要注意:类内部,引用类自己的变量和函数,一定要前面加上$this->,否则会出错,并且没有任何提示的。。。
比如:
转载请注明:在路上 » 【记录】php中如何写类和如何使用类