草庐IT

php - 在父函数中调用子对象

coder 2024-04-12 原文

我想知道我是否可以在父函数中调用子对象。像这样:

   class Parent {

          public function A() {
             << I want to call the object here >>
             // Some code 
          }
   }

   Class Child extends Parent {

          public function B() {
            // Some code
          }
   }

   $Child = new Child();
   $Child -> B();

这两个类在不同的文件中。我的子类正在使用函数 B() 与我的数据库建立连接。在我的父类 A() 中,我试图插入从填写表单中收到的数据,但我需要连接到数据库,但我不知道如何调用该对象。注意:当我在同一个类中同时拥有这两个函数时,我的代码可以正常工作。

我没有找到解决方案,所以我会尝试并发布我的真实代码:

 class db_connect extends Model
 {
    private $dbname = "...";
    private $dbuser = "...";
    private $dbpass = "...";
    private $dbhost = "...";
    public $dbc;

    public function Connect()
    {
        $this->dbc = mysqli_connect($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname);

    if($this->dbc === false){
        die("ERROR: Could not connect. " . mysqli_connect_error());    
    }}
}

所以这是 Class Child from Above 而 Connect() 是 B()。

现在是 parent

class Model 
{
      public $query;
      public $result;

      public function proccess_data($marca,$model,$pret,$descriere){
         << I am trying to make a connection here from config.php using the function Connect() >>
         $this->query = "INSERT INTO autoturisme (autoturism_id, marca, model, pret, descriere) " .
     "VALUES (NULL, '$marca', '$model', '$pret', '$descriere')";
         $this->result = mysqli_query(<<Also here I would need the connection>>, $this->query) 
    or die(mysqli_error(<<And here>>));
         if($this->result == 1){
         echo "<br/>Your data were processed";
    } else {
         echo "<br/>We are sorry but an error occurred";
    }
        $this->close_db();

}

mysqli_query 中,我需要一个参数作为 mysqli,它是到我的数据库的连接。该参数位于子类 $dbc 中,并在函数 Connect() 中调用:$this->dbcmysqli_error 也是如此。希望这能让事情更清楚 :)。

最佳答案

考虑到您已标记此 oop我会咬。

db_connect 没有理由扩展Model。更不用说没有理由称某些东西为 Model,它不会告诉任何人任何东西,因此对于任何东西来说都是一个非常蹩脚的名字。

其次,据我所知,您没有理由在开始时包装 mysqli。通过包装这样的对象你会得到什么。 mysqli 带有开箱即用的面向对象的接口(interface)。

最后,当你摆脱了你正在进行的那个奇怪的继承树时,你应该将数据库连接注入(inject)到需要它的类中。像这样的东西:

class Car
{
    // why do you need a `$query` member when you are not going to use it?
    // same for `$result`

    private $dbConnection;

    public function __construct(mysqli $dbConnection)
    {
        $this->dbConnection = $dbConnection;
    }

    public function add($marca, $model, $pret, $descriere)
    {
        $query = 'INSERT INTO autoturisme';
        $query.= ' (marca, model, pret, descriere)';
        $query.= ' VALUES';
        $query.= ' (?, ?, ?, ?)';

        $stmt = $this->dbConnection->prepare($query);

        $stmt->bind_param('ssss', $marca, $model, $pret, $descriere);

        if (!$stmt->execute()) {
            throw new \Exception('We are sorry but an error occurred');
        }
    }
}

$mysqli = new mysqli('localhost', 'user', 'pass', 'dbname');

$car = new Car($mysqli);

try {
    $car->add('BMW', '325', 'dunnowhatthismeans', 'description?');
} catch(\Exception $e) {
    echo $e->getMessage();
}

另请注意,您的代码很可能容易受到 SQL 注入(inject)攻击。

关于php - 在父函数中调用子对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38209806/

有关php - 在父函数中调用子对象的更多相关文章

  1. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  2. ruby-on-rails - 按天对 Mongoid 对象进行分组 - 2

    在控制台中反复尝试之后,我想到了这种方法,可以按发生日期对类似activerecord的(Mongoid)对象进行分组。我不确定这是完成此任务的最佳方法,但它确实有效。有没有人有更好的建议,或者这是一个很好的方法?#eventsisanarrayofactiverecord-likeobjectsthatincludeatimeattributeevents.map{|event|#converteventsarrayintoanarrayofhasheswiththedayofthemonthandtheevent{:number=>event.time.day,:event=>ev

  3. ruby-on-rails - 如何验证非模型(甚至非对象)字段 - 2

    我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss

  4. Ruby 写入和读取对象到文件 - 2

    好的,所以我的目标是轻松地将一些数据保存到磁盘以备后用。您如何简单地写入然后读取一个对象?所以如果我有一个简单的类classCattr_accessor:a,:bdefinitialize(a,b)@a,@b=a,bendend所以如果我从中非常快地制作一个objobj=C.new("foo","bar")#justgaveitsomerandomvalues然后我可以把它变成一个kindaidstring=obj.to_s#whichreturns""我终于可以将此字符串打印到文件或其他内容中。我的问题是,我该如何再次将这个id变回一个对象?我知道我可以自己挑选信息并制作一个接受该信

  5. ruby - 在没有 sass 引擎的情况下使用 sass 颜色函数 - 2

    我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re

  6. ruby-on-rails - 如果 Object::try 被发送到一个 nil 对象,为什么它会起作用? - 2

    如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象

  7. ruby-on-rails - 未在 Ruby 中初始化的对象 - 2

    我在Rails工作并有以下类(class):classPlayer当我运行时bundleexecrailsconsole然后尝试:a=Player.new("me",5.0,"UCLA")我回来了:=>#我不知道为什么Player对象不会在这里初始化。关于可能导致此问题的操作/解释的任何建议?谢谢,马里奥格 最佳答案 havenoideawhythePlayerobjectwouldn'tbeinitializedhere它没有初始化很简单,因为你还没有初始化它!您已经覆盖了ActiveRecord::Base初始化方法,但您没有调

  8. ruby - 如何在 Rails 4 中使用表单对象之前的验证回调? - 2

    我有一个服务模型/表及其注册表。在表单中,我几乎拥有服务的所有字段,但我想在验证服务对象之前自动设置其中一些值。示例:--服务Controller#创建Action:defcreate@service=Service.new@service_form=ServiceFormObject.new(@service)@service_form.validate(params[:service_form_object])and@service_form.saverespond_with(@service_form,location:admin_services_path)end在验证@ser

  9. ruby-on-rails - 在 ruby​​ 中使用 gsub 函数替换单词 - 2

    我正在尝试用ruby​​中的gsub函数替换字符串中的某些单词,但有时效果很好,在某些情况下会出现此错误?这种格式有什么问题吗NoMethodError(undefinedmethod`gsub!'fornil:NilClass):模型.rbclassTest"replacethisID1",WAY=>"replacethisID2andID3",DELTA=>"replacethisID4"}end另一个模型.rbclassCheck 最佳答案 啊,我找到了!gsub!是一个非常奇怪的方法。首先,它替换了字符串,所以它实际上修改了

  10. 使用 ACL 调用 upload_file 时出现 Ruby S3 "Access Denied"错误 - 2

    我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file

随机推荐