/    Sign up×
Community /Pin to ProfileBookmark

Call method bypass construct

I have a class, which has a __constructor method. I use this constructor method in several places so don’t want to remove it yet. I could make a create method instead and this is what I’ll eventually do.

I want to however also have a getById method where my object is created by a database query

[code]
class person{
private string $personName;
public function __construct($personName){
$this->personName = $personName;
}
public function getById($id){
//do database stuff
$this->personName = $row[‘personName’];
}
}
[/code]

On my pages I want this

[code]
$person = new person;
$person->getById($_GET[‘id’]);
[/code]

But I’m getting this error **Fatal error: Uncaught ArgumentCountError: Too few arguments to function**

Is there a way around this?

to post a comment
PHP

1 Comments(s)

Copy linkTweet thisAlerts:
@NogDogNov 28.2021 — Simplest solution would be to make the constructor's argument optional:
<i>
</i>function __construct($personName = null) {
if(isset($personName)) {
$this-&gt;personName = $personName;
}
}

Whether or not that's the _best_ thing...that would depend on all the underlying requirements, etc. :)
×

Success!

Help @kiwis spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.18,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...