Welcome Guest, Not a member yet? Register   Sign In
potentially polymorphic call with model instance inside model function
#1

(This post was last modified: 10-31-2022, 12:54 AM by objecttothis. Edit Reason: word choice )

I'm porting a CI3 app to CI4 and need to call one model method inside another model method.  Can someone tell me why this produces no warning:

PHP Code:
public function get_value(): int
 
{
 
$this->sale model('Sale');
 return 
$this->sale->get_quote_number_for_year();
 }


But if I do this:

PHP Code:
public function get_value(): int
 
{
 
$sale model('Sale');
 return 
$sale->get_quote_number_for_year();
 }


I get a warning from PhpStorm
Potentially polymorphic call. Model does not have members in its hierarchy

The function signature for get_quote_number_for_year() is
public function Sale::get_quote_number_for_year($year = '', $start_from = 0) int
Reply
#2

What if model(Sale::class)?
Reply
#3

(10-31-2022, 01:47 AM)kenjis Wrote: What if model(Sale::class)?

with
PHP Code:
$sale model(Sale::class); 

The warning goes away. The puzzling thing for me is that the documentation (https://codeigniter.com/user_guide/models/model.html) doesn't give examples this way but gives examples using $modelName =

Maybe this has to do with me instantiating a model inside a model instead of a class? What is the best practice here? $this->sale = model('Sale') or $sale = model(Sale::class)?
Reply
#4

(This post was last modified: 10-31-2022, 04:51 AM by kenjis.)

Did you specify the type for $this->sale ?

model(Sale::class) and model('Sale') are exactly the same for CodeIgniter,
but a bit different for PHPStan.

I recommend model(Sale::class) because PHPStan knows the return value type (Sale::class).
And the type is correct more than 99%.


See also https://www.jetbrains.com/help/phpstorm/...-call.html
Reply
#5

(10-31-2022, 02:43 AM)kenjis Wrote: Did you specify the type for $this->sale ?

model(Sale::class) and model('Sale') are exactly the same for CodeIgniter,
but a bit different for PHPStan.

I recommend model(Sale::class) because PHPStan knows the return value type (Sale::class).
And the type is correct more than 99%.


See also https://www.jetbrains.com/help/phpstorm/...-call.html

I did not specify the type for $this->sale. Just what you see in the code I posted.

I do have a use statement at the top of the file

PHP Code:
namespace App\Models\Tokens;

use 
app\Models\Sale
Reply
#6

(This post was last modified: 10-31-2022, 02:51 PM by kenjis.)

<?php

namespace App\Models;

I cannot reproduce the warning.
I got no warning.

PHP Code:
use CodeIgniter\Model;

class 
Sale extends Model
{


PHP Code:
<?php

namespace App\Models;

use 
CodeIgniter\Model;

class 
Test extends Model
{
    public function get_value(): int
    
{
        $sale model('Sale');

        return $sale->get_quote_number_for_year();
    }


I don't know why you got the warning.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB