ternary operator syntax error in class [closed] - php

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I want to use ternary operator to assign two different values to the class variable.
I have following code sample where i am getting fatal error.
class test {
public $data = (true) ? "working" : "not working"; //Parse error: syntax error, unexpected '(' in C:\xampp\htdocs\Faltu\test.php on line 15
function __construct() {
echo $this->data;
}
}
$test = new test();
I have tried without class and it's working fine but in class I'm getting error.
Can anyone guide me how to achieve this?
Thanks in advance

You may only assign constant values when declaring properties, you cannot perform logical operations, like a ternary.
You can perform your logic in your __construct function:
class test {
public $data = NULL;
function __construct() {
$this -> data = true ? "working" : "not working";
echo $this -> data; // working
}
}
$test = new test();
From the documentation:
This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

it works have a look
class test {
public $data = NULL;
function __construct() {
echo $this -> data = true ? "working" : "not working"; //working
}
}
$test = new test();

Related

Does PHP have keyword or feature that shortens repetition like jquery $(this)? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Does PHP have keyword or feature that shortens code and repetition like jquery $(this)?
For example
// How to avoid typing same variable twice
echo isset($_POST['foo']) ? $_POST['foo'] : '';
In Jquery
<script>
// Avoid typing $("#button-element") again
$("#button-element").click(function() {
$(this).css("border-color", "#000");
});
</script>
No. And that code wouldn't work in JS either.
In JS, this is -- roughly speaking -- the object that the current function was called as a method on. It is not "the last thing I mentioned". The JS equivalent of your second code:
_POST['foo'] ? this : ''
would return an object if _POST['foo'] were set. It would not return the value of _POST['foo'].
There is no variable like the one you're looking for in any language I've ever used.
of course it does! you need to construct this across a class.
It works about the same as in javascript ES6 class.
$number = 4;
$This = new demoThis($number);
$This->multiplyThis(4);
class demoThis {
private $number;
private $factor;
public $result;
public function __construct($number) {
$this->number = $number;
}
function multiplyThis($factor) {
$this->factor = $factor;
$this->result = $this->number * $this->factor;
return $this->result;
}
}
echo isset($_POST['foo']) ? $This->result : '';

OOP PHP. Syntax Undefined property [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I have an error probably because of the syntax and I cant find how to do it correctly.
This is my code
function myFunction($id = 'ID')
{
if (!$this->$id) {
// TO DO SOMETHING
}
}
I have the next error
Notice: Undefined property: Base::$ID ..... on line 278
I tried with
if (!$this->{$id}) {
but nothing
anyone know the correct syntax is. I cant find it on google neither.
You may use property_exists instead of using direct access if(!$this->$id):
function myFunction($id = 'ID')
{
if (!property_exists($this, $id)) {
// TO DO SOMETHING
}
}
If you are defining a property on your class, you should access it like such:
$this->id
not
$this->$id
I created an example how your code might work, and I kept the idea of accessing a property by a string. The first step is to have the class actually have a field named "ID". I set this field value in the constructor.
class My {
private $ID;
public function __construct($id) {
$this->ID = $id;
}
public function myFunction($id='ID'){
if(!property_exists($this, $id)){
echo "$id not found";
} else {
echo $this->$id;
}
}
}
$my = new My(4);
$my->myFunction();
Simply use
if(!$this->id) {
or
if(!$id) {
Try this method to get the output.
$this->id
or
$id

php fail to print an array of object [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
My php code is:
<?php
class Product {
var $product_name;
var $retailer;
function __constructor($product, $retailer) {
$this->product_name = $product;
$this->retailer = $retailer;
}
function getProduct() {
return $this->product_name;
}
}
$product_arr = array();
for ($f = 0; $f < 100; $f++) {
array_push($product_arr, new Product("asd", "xcxcxc"));
}
print_r($product_arr);
?>
The code is pretty simple, I have a class called "Product", I build an array consists of 100 Product object, but when I tried to print the array, I found out all the object's product_name and retailer fields are empty. Not sure why this happens.
Wrong name:
function __constructor($product, $retailer) {
^^^
PHP's standard constructor name is simply __construct (no or). So you never actually called a constructor, which means your variable assignments never executed.

Class constructor creates new class fields with variable names? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I'm trying to initialize a class through a constructor with PHP 5.5.13 but am getting some weird results. The setup is like this:
class foo{
public $bar;
public $top;
public $bot = array();
function __construct($bar, $top){
$this->$bar = $bar;
$this->$top = $top;
}
}
$phonebook = array();
$user_input = $_POST['query'];
if(/* regex match */){
foreach($valid_input[0] as $arr){
$name_and_number = explode(" ", $arr);
$phonebook[] = new foo($name_and_number[0], (int) $name_and_number[1]); //e.g. Bob, 123
var_dump($phonebook[count($phonebook)-1]);
}
}
The weird part is now, however that phonebook's var_dump returns:
object(foo)#1 (5) { ["bar"]=> NULL ["top"]=> NULL ["bot"]=> array(0) { }
["Bob"]=> string(3) "Bob" ["123"]=> int(123) }
Running:
echo "$phonebook[0]->$bar";
echo "$phonebook[0]['Bob']"; //Since a Bob field apparently exists?
echo "$phonebook[0]->$Bob"; //Just to test if maybe a $Bob variable has been declared?
All return an empty page. I'm at a loss here. Is my constructor setup weird? Or the way I try to access the variables?
What you need to do is get rid of the second $ sign like so
class foo{
public $bar;
public $top;
public $bot = array();
function __construct($bar, $top){
$this->bar = $bar;
$this->top = $top;
}
}
The reason why you're seeing the 'weird' results is because the value of $bar and $top are evaluated dynamically and will be used to create a new named property. Resulting, in your case, to a property named 'Bob' and '123'
The problem is in these lines:
function __construct($bar, $top){
$this->$bar = $bar;
$this->$top = $top;
}
$this->$bar refers to the property that is named after the value of bar. So if you pass the name Bob, you actually set the property Bob to 'Bob'.
Your intention, of course, is to set the property bar. To do that, remove the $ sign. It must be omitted for properties:
$this->bar = $bar;
So it has nothing to do with the constructor, it's just the way you use properties anywhere. In a constructor or even out of class methods. echo "$phonebook[0]->$bar" should also be echo "$phonebook[0]->bar";.
Personally I think this is a weird and counter intuitive syntax, but I've once been in a serious fight over it with a PHP afficionado, so I don't dare to bring it up again. Just live with it. ;)

How can I use arrays within objects? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I was making a class in PHP for validation of a contact form, when I hit a problem. I eventually tracked it down to an array within the class, and wrote a test script to try to solve the problem:
<?php
class Object {
public $testArray = array(5);
function __construct() {
$testArray[] = 7;
}
function addNumber() {
$testArray[] = mt_rand(10,20);
}
function returnArray() {
return var_dump($testArray);
}
}
$object = new Object;
$object->addNumber();
echo($object->returnArray());
var_dump($object->testArray);
This outputs NULL array(1) { [0]=> int(5) }.
I am confused as to why this does not work. Eventually I would like the array to be private, but I can't find a way similar to get and set in C#. Any ideas?
Give this a go:
class Object {
public $testArray = array(5);
function __construct() {
$this->testArray[] = 7;
}
function addNumber() {
$this->testArray[] = mt_rand(10,20);
}
function returnArray() {
return var_dump($this->testArray);
}
}
You have to reference the class variable using $this - otherwise it'll try to set a variable local to the function you're in.
You can use PHP's magic __set() and __get() methods for similar functions to C# that you mentioned: PHP Overloading.
$testArray[] = mt_rand(10,20);
Should be:
$this->testArray[] = mt_rand(10,20);
$testArray is just another local variable (local to the function, no the class). If it has no value it is null. This is consistent with the output you're seeing. $object->testArray is never modified.
You have to access class variables using $this. So $testArray should be $this- >testArray.

Categories