This question already has answers here:
Are objects in PHP assigned by value or reference?
(3 answers)
Are PHP5 objects passed by reference? [duplicate]
(8 answers)
Closed 2 years ago.
what i want to ask is, why the $character property of Forest class is a reference instance to $character Object not the clone ?
<?php
// example code
Class Ogre
{
protected $position = 0;
protected $name;
public function setPosition($position)
{
$this->position = $position;
}
public function getPosition()
{
return $this->name.' position is at axis '.$this->position.'.';
}
public function setName($name)
{
$this->name = $name;
}
public function walk($step)
{
$this->position += $step;
return $this;
}
public function getInfo()
{
return 'Type: '.self::class.', Name: '.$this->name;
}
}
class Forest
{
protected $character;
public function __construct($character)
{
// var_dump($character);
$character->setPosition(55);
}
public function getName()
{
return 'Theme Name : Forest';
}
}
$character = new Ogre();
$character->setName('Magi');
echo $character->getPosition(); //the position is 0 i've never defined the position
$theme = new Forest($character);
echo $character->getPosition(); //it shows 55 because i defined it inside Forest constructor
Related
This question already has answers here:
Access variable from scope of another function?
(3 answers)
Closed 5 years ago.
I have this code
class foo
{
function one()
{
$number = 1;
}
function two()
{
echo $number;
}
}
And i want to call $number from function one() on function two().
Is it possible to do this ?
Hello Mfdsix Indo,
Try this code,
class foo
{
function one()
{
$number = 1;
return $number;
}
function two()
{
echo $this->one();
}
}
OR
class foo
{
private $number;
function one()
{
$this->number = 1;
}
function two()
{
echo $this->number;
}
}
I hope my answer id helpful.
If any query so comment please.
This question already has answers here:
Enumerations on PHP
(39 answers)
Closed 1 year ago.
I basically want an enum-like class in PHP. My enum should have a few values (they are all static). Let's say I want to have an enum that has an ID (the ID must never, ever change), and a name (the name must not change during runtime, it can change during compile-time -- e.g. from changes made to the code). The state must not have any side-effects (i.e. they are only getters and instance variables cannot be changed). A state must also not be created during runtime except when initializing the class.
For my concert example, I have three possible states: OPEN, CLOSED, and UNKOWN:
class MyState {
const STATE_OPEN = new MyState(1, "open");
const STATE_CLOSE = new MyState(2, "closed");
const STATE_UNKOWN = new MyState(3, "unkown");
private $name;
private $state;
private function __construct(int $state, string $name) {
$this->state = $state;
$this->name = $name;
}
public function getName() : string {
return $this->name;
}
public function getState() : int {
return $this->state;
}
public function getStateByID(int $state) : MyState { ... }
public function getStateByName(string $name) : MyState { ... }
}
I want to refer to each state unambiguously in my code (MyState::STATE_OPEN, etc). This should also ensure that a compiler/linter/etc can verify that the state actually exists (there is no guarantee that getStateByID does not throw an exception).
There are also some (de)serializers that can load a state after it has been saved (by using the never changing ID).
Unfortunately, I cannot set const or static instance variables if their object is from the same class. I get the following error:
Constant expression contains invalid operations
How can this be best accomplished in PHP? I know I can easily create an enum with just an int (class MyState { const STATE_OPEN = 1; }) but that has a major disadvantage: the enum is not an object and thus cannot have methods. I cannot use type hinting this way and I might pass an invalid enum. E.g., function takeMyState(int $state) can actually use an enum that has never been defined.
Replace your const lines
const STATE_OPEN = new MyState(1, "open");
by public functions:
public function STATE_OPEN() { return new MyState(1, "open"); }
resulting in an example program like this:
class MyState {
public function STATE_OPEN() { return new MyState(1, "open"); }
public function STATE_CLOSED() { return new MyState(2, "closed"); }
public function STATE_UNKNOWN() { return new MyState(3, "unknown"); }
private $name;
private $state;
private function __construct(int $state, string $name) {
$this->state = $state;
$this->name = $name;
}
public function getName() : string {
return $this->name;
}
public function getState() : int {
return $this->state;
}
}
$state = MyState::STATE_CLOSED();
echo $state->getName() . "(" . $state->getState() . ")\n";
This question already has answers here:
PHP json_encode class private members
(9 answers)
Closed 3 days ago.
I have a class:
class A {
protected $nome;
public function getNome() {
return $this->nome . " exemplo";
}
public function setNome($nome) {
$this->nome = $nome;
}
}
When i use the code:
$r = new A();
$r->setNome("My");
json_encode($r);
the code not returns because of the protected property, if the property is public the code returns but does'nt returns correctly.
As per the definition of class, we can access only public members outside class. So make $nome for public
class A {
public $nome;
public function getNome() {
return $this->nome . " exemplo";
}
public function setNome($nome) {
$this->nome = $nome;
}
}
$r = new A(); print_r($r);
$r->setNome("My");
echo json_encode($r);
OR
Return results to json_encode(if you don't make $Nome public), see the example:
$r = new A();
$r->setNome("My");
echo json_encode($r->getNome());
This question already has answers here:
PHP method chaining or fluent interface?
(10 answers)
Closed 9 years ago.
I am new to php and crating classes for my project . I have reached this far ..
$db->select('id');
$db->from('name');
$db->where("idnum<:num");
$db->bindparamers(':num',100);
$rows=$db->executeQuery();
I wana know to create methods such that i can use all thing at once like below
$db->select('id')->from('name')->where('idnum>100')->executeQuery();
I have tried searching but not getting what exactly i should search for
here is my class structure
class Dbconnections
{
//For Complex Queries
public function select($items)
{
}
public function from($tablenames)
{
}
public function where($arr)
{
}
public function orderby($order)
{
}
public function bindparamers($parameter,$value)
{
}
public function executeQuery()
{}
}
What changes i need to make to use it as :
$db->select('id')->from('name')->where('idnum>100')->executeQuery();
It's called method chaining and in your case can be achieved by returning $this from each method.
class Dbconnections
{
public function select($items)
{
// ...
return $this;
}
public function from($tablenames)
{
// ...
return $this;
}
public function where($arr)
{
// ...
return $this;
}
public function orderby($order)
{
// ...
return $this;
}
public function bindparamers($parameter,$value)
{
// ...
return $this;
}
public function executeQuery()
{
// ...
return $this;
}
}
This question already has an answer here:
Overloading method of comparison for custom class
(1 answer)
Closed 9 years ago.
I was wondering if there is a way to create a class in PHP that when compared with other variables a default value is used instead of the class itself? such that:
class Test {
private $name;
private $val;
public function __construct($name, $val) {
$this->name = $name;
$this->val = $val;
}
public __default() {
return $val;
}
public function getName() {
return $name;
}
}
then I could use a function like __default when I compare it to another value such as:
$t = new Test("Joe", 12345);
if($t == 12345) { echo "I want this to work"; }
the phrase "I want this to work" will print.
As far as I know this is not possible. The closest thing you're looking for is the __toString() method to be set on the class.
http://php.net/manual/en/language.oop5.magic.php
PHP might try to convert it to an Integer, but I'm not sure if there are class methods to accomplish this. You could try string comparison.
<?php
class Test {
private $name;
private $val;
public function __construct($name, $val) {
$this->name = $name;
$this->val = $val;
}
public function __toString() {
return (string)$this->val;
}
public function __toInt() {
return $this->val;
}
public function getName() {
return $this->name;
}
}
$t = new Test("Joe", 12345);
if($t == '12345') { echo "I want this to work"; }
The __toString magic method will do what you want with some caveats:
class Test {
private $name;
private $val;
public function __construct($name, $val) {
$this->name = $name;
$this->val = $val;
}
public function __toString() {
return $this->val;
}
public function getName() {
return $this->name;
}
}
Objects can't be directly cast to an integer so will always get a when comparing to an integer but if you cast either side of the comparison to a string it will work as expected.
if($t == 12345) // false with a warning about can't cast object to integer
if((string)$t == 12345) // true
if($t == "12345") // true
Implement __toString() in your class.
Like:
class myClass {
// your stuff
public function __toString() {
return "something, or a member property....";
}
}
Your object will unlikely equals integer. But you can implement something similar to Java's hashCode() - a class method that do some math to produce numeric hash - a return value based on i.e. its internal state, variables etc. Then compare these hash codes.
Why not something along this line:
class Test {
private $name;
private $val;
public function __construct($name, $val) {
$this->name = $name;
$this->val = $val;
}
public __default() {
return $val;
}
public compare($input) {
if($this->val == $input)
return TRUE;
return FALSE;
}
public function getName() {
return $name;
}
}
$t = new Test("Joe", 12345);
if($t->compare(12345)) { echo "I want this to work"; }
From other answers it appears there is not a built in function to handle this.