0

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?

miorey
  • 828
  • 8
  • 19
helpsergio
  • 33
  • 1
  • 6
  • 4
    If the constructor is protected, there's no way to instantiate that class from the outside. Why is the constructor protected to begin with? What exactly are you trying to accomplish? – M. Eriksson Dec 17 '21 at 17:10
  • You have some real syntactical issues `getWhatINeed` is declared inside the `__construct` of `myClassA1` – miorey Dec 17 '21 at 17:10
  • @M.Eriksson he can it depends if `Jsonable ` contains something like `public static function getClass() { return new static(); }` – miorey Dec 17 '21 at 17:17
  • If for some reason you cannot change the access from protected, and you can't add a method to get around that, and you cannot [subclass it](https://stackoverflow.com/a/20334749/231316), your only other option is probably [reflection](https://stackoverflow.com/a/28352585/231316), which I would consider a last resort – Chris Haas Dec 17 '21 at 17:51
  • @miorey I forgot the close bracket } before getWhatINeed() – helpsergio Dec 17 '21 at 19:52
  • @ChrisHaas I will try what you suggested on Monday Morning, because I cannot change the access from proteted. I do have a getFunction but I don't know how to access it. – helpsergio Dec 17 '21 at 19:57
  • @ChrisHaas I extended A1 class with the method I need into A2 but now I get "Call to undefined method classNeeded::getWhatINeed() – helpsergio Dec 18 '21 at 13:04
  • @miorey - That's not instantiating it from the outside. That's a method that creates an instance from _inside_ the class and just returns it. When loading a class through CI's loader class, like `$CI->load->model("myClassA1")`, CI will try and instantiate the class with: `new $name`. – M. Eriksson Dec 18 '21 at 13:31

0 Answers0