John Davidson

codeigniter - PHP Call to protected (from another model)::__construct() from context

0 comments
Message:


Please be kind and ask me more information if you need. Please be sure I tried all I could not to create a yet another question


I need access to a method of a model, inside a parallel model.


model class A1;


<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class myClassA1 extends Jsonable
{
protected $myClassA1;
protected function __construct(){

public function getWhatINeed(){
return $this->getWhatINeed;
}

}

I need access to A2's model, however please notice A2 is protected class.


class myClassA2 extends Jsonable
{
protected $myClassA2;

function __construct() {
parent::__construct();
$CI =& get_instance();
$CI->load->model("myClassA1")

$this->myClassA1->getWhatINeed();

I also tried the construct and the $this->load('model') but I would always get load() on null.


Here is the error message:



PHP Call to protected (from another model)::__construct() from context



Here is the question: Any way around this and use A2 protected method without changing A2 class from protected?



My Answer:
In CodeIgniter, you cannot directly access a protected method from one model to another model. Protected methods are only accessible within the same class or its subclasses.

One way to achieve this is by creating a public method in Model A1 that calls the protected method you want to access. Then, you can call this public method from Model A2.

For example, in Model A1:

php
class A1 extends CI_Model {
protected function myProtectedMethod() {
// Your code here
}

public function callMyProtectedMethod() {
return $this->myProtectedMethod();
}
}


And in Model A2:

php
class A2 extends CI_Model {
public function someMethod() {
$modelA1 = new A1();
$result = $modelA1->callMyProtectedMethod();
// Use $result as needed
}
}


By doing this, you can indirectly access the protected method from Model A1 in Model A2.

Rate this post

3 of 5 based on 8681 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us