在一个类中调用多个函数

时间:2018-06-26 11:56:42

标签: php

我试图提取来自segment.php中的类段定义的所有函数的内容。并从home_segment.php的类段中调用所有三个函数 这是从一个类调用多个函数的正确方法吗?

segment.php

<?php
$mysqli = mysqli_connect("localhost","root","","square");
 $cid = required_param('id', PARAM_INT);
 class segment
 {   
   public function unitseg_set1($cid)
   {          
     $subject = $mysqli->query('SELECT * FROM order_subject WHERE id='.$cid.'');     
     while($row=$subject->fetch_array() )
     {
        echo '<div>'.$row['chem_name'].'</div>';
     }   
   }

   public function unitseg_set2($cid)
   {          
     $subject = $mysqli->query('SELECT * FROM order_subject WHERE id='.$cid.'');     
     while($row=$subject->fetch_array() )
     {
        echo '<div>'.$row['physiotherapy_nn'].'</div>';
     }   
   }   

   public function unitseg_set3($cid)
   {          
     $subject = $mysqli->query('SELECT * FROM order_subject WHERE id='.$cid.'');     
     while($row=$subject->fetch_array() )
     {
        echo '<div>'.$row['commun_gg'].'</div>';
     }   
   }   
 }
 ?>

home_segment.php

<?php


    require_once('segment.php');
   $account1 = segment::unitseg_set1($cid);
   $account2 = segment::unitseg_set2($cid);
   $account3 = segment::unitseg_set3($cid);

   echo $account1.$account2.$account3;
 ?>

2 个答案:

答案 0 :(得分:2)

这些方法未定义为static,因此您不能使用::语法(http://php.net/manual/en/language.oop5.paamayim-nekudotayim.php)。您必须首先将该类实例化为一个对象,然后可以使用->运算符来调用这些方法。您将必须有权访问$cid变量,以便您可以将其传递。

我不得不提到,您的SQL查询对SQL注入攻击非常开放。请查询PDO和参数化查询。 https://phpdelusions.net/pdo

<?php

require_once('segment.php');
$cid = required_param('id', PARAM_INT);
$segment = new segment();
$account1 = $segment->unitseg_set1($cid);
$account2 = $segment->unitseg_set2($cid);
$account3 = $segment->unitseg_set3($cid);

echo $account1.$account2.$account3;

答案 1 :(得分:1)

::用于定义为static的方法。如static中那样将您的方法定义为public static function ...,或者按以下方式实例化该类:

require_once('segment.php');
$segment = new segment();
$account1 = $segment->unitseg_set1($cid);
$account2 = $segment->unitseg_set2($cid);
$account3 = $segment->unitseg_set3($cid);

echo $account1.$account2.$account3;

而且,正如waterloomatt所指出的,您对SQL injection持开放态度。您需要使用准备好的语句,而不是将变量连接到查询中。参见How can I prevent SQL injection in PHP?