PHP:如何在类之外调用函数

时间:2017-02-28 10:49:22

标签: php logging

我正在尝试将“记录器”实现到我正在处理的Web工具中,这基本上是一个看起来像这样的php文件:

<?php
function makePost($post) {
    $file = fopen("log.txt", "a") or die ("Unable to open file");

    $today = date("Y/m/d-h:i");
    fwrite($file, $today . "\n====================================");

    fwrite("\n" . $post);
    fwrite("\n====================================");

    fclose($file);
}

我试图从“网络工具”中的其他位置打电话,当我试图从一个类中调用它来处理数据库并且我试图调用时,问题出现了上面的函数似乎程序只是停在它的轨道上,而其余的函数(和记录器本身)都没有被执行。

我尝试调用记录器的简化类:

class handleAccounts {
    function loginValidation() {
        require_once("log.php");
        makePost("A login was attempted");

        // Some more code that isn't executed
    }
}

2 个答案:

答案 0 :(得分:0)

第8行和第9行的MakePost函数出错。通过注释第8行和第8行解决了这个问题。 9。

function makePost($post) {
    $file = fopen("log.txt", "a") or die ("Unable to open file");

    $today = date("Y/m/d-h:i");
    fwrite($file, $today . "\n====================================");

//    fwrite("\n" . $post);
//    fwrite("\n====================================");

    fclose($file);
}

答案 1 :(得分:0)

像这样改变

<?php
function makePost($post) {
  $today = date("Y/m/d-h:i");
  $sep = str_repeat‌​("=",20);
  $res = file_put_contents('log.txt',"$today\n$sep\‌​n$post\n$sep\n",FILE_A‌​PPEND);
  if(!$res){
    die ("Unable to open and write to file");
  }
}

<?php
require_once("log.php");
class handleAccounts {
 function loginValidation() {
    makePost("A login was attempted");
    // Some more code that isn't executed
 }
}

'log.txt'的注意事项: 如果例如log.php位于/foo/bar/log.php下且日志文件应位于/foo/log/log.txt下,则您可以dirname(__FILE__).'/../log/log.txt'而不只是'log.txt',所以您将始终写入public partial class Gallery { public int Id { get; set; } public int CategoryId { get; set; } public string ImageTitle { get; set; } public string Image { get; set; } public virtual Category Category { get; set; } } public Category() { this.Galleries = new HashSet<Gallery>(); } public int Id { get; set; } public string CategoryName { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<Gallery> Galleries { get; set; } } 同一文件夹中的同一文件。