I'm working on a PHP Class, one of the required fields for the Class is (DropoffType)
The answer to that is REGULARPICKUP.
Can I write this inside the class and put "=" to the REGULARPICKUP?
Example:
protected $DropoffType = 'REGULARPICKUP';
Sure you can
class MyClass
{
protected $DropoffType = 'REGULARPICKUP';
}
or do it in the constructor (this depends on your specific case whether this is the way to go):
class MyClass
{
protected $DropoffType;
public function __construct($Dropofftype = 'REGULARPICKUP')
{
$this->DropoffType = $Dropofftype;
}
}
Or if you have a set function:
class MyClass
{
protected $DropoffType;
public function setDropoffType($Dropofftype = 'REGULARPICKUP')
{
$this->DropoffType = $Dropofftype;
}
}
Related
I have a base class which sets up's other extending controllers like this:
class BaseController extends Controller
{
public $globalCurrencies;
public $globalLanguages;
public function __construct()
{
$this->globalCurrencies = $this->getCurrencies(); // this works
$this->globalLanguages = $this->getLanguages(); // this works
}
}
And I use one of helpers to extend this class like this:
class SessionHelper extends BaseController
{
public $test;
public function __construct()
{
parent::__construct(); // fire parent aka basecontroller construct
$this->test = $this->globalCurrencies; // this works (variables are set)
echo '__construct: '.$this->test; // this even displays it
}
public function getCurrencies()
{
dd('method'.$this->test); // NOT WORKING
}
public function getCurrentCurrency()
{
return $this->getCurrencies()->where('id', Session::get('currencyId'))->first() ?? null;
}
}
Later on code is used in model:
class Product extends Model
{
protected $table = "products";
public $timestamps = true;
public $sessionHelper;
public function __construct()
{
$this->sessionHelper = new SessionHelper;
}
public function getPrice($conversion_rate = null)
{
return number_format($this->price_retail / $this->sessionHelper->getCurrentCurrency()->conversion_rate, 2);
}
}
Have any body idea why I can access in construct variable but not in method? If i remember correctly construct is fired first so everything after should have access to it.
Declare $test variable as private out side the constructor. Inside the constructor keep it the way you are doing it right now and then make a setter and getter for the test variable.
class testObject
{
private $test;
function __construct($test)
{
$this->test= $this->globalCurrencies;
}
// test getter
function getTest()
{
return $this->test;
}
}
Change your method to be;
public function getCurrencies()
{
dd('method', $this->test);
}
You can not concatenate strings and objects/arrays.
If that doesn't resolve the issue - check the laravel.log
I'm really bad at OOP and I can't work out this inherited code I've been given.
This is part of the generic Model class;
abstract class Model
{
protected static $_tableName = false;
protected static $_itemName = false;
public static function tableName()
{
return static::$_tableName;
}
public static function itemName()
{
return static::$_itemName;
}
How do I set the tablename in the Class that I have created???;
class Payments extends Model {
//public $_tableName;
public function __construct()
{
$this->$_tableName = 'payments'; //line 13
}
}
I get an error Undefined variable: _tableName in /var/www/html/lib/Local/Models/Payments.php on line 13 when I don't set it as a parameter. and an error Cannot redeclare static XXX\Model::$_tableName when I do.
UPDATE
When I try to use the find method with this abstract Model, it's not setting the tableName;
public static function find($idOrWhere = false, $params = array(), $limit = false)
{
$sql = "SELECT * FROM " . static::tableName();
I don't know how to set that now. It just ignores what I have put in my class.
You have to remove the $ when accessing a class property:
class Payments extends Model
{
public function __construct()
{
$this->_tableName = 'payments';
}
}
Indeed this is irritating, but that's the way php syntax works.
With static class you need to use the self keyword to initialize property in class:
class Foo {
static $bar;
}
Foo::$bar = array(…);
or
class Foo {
private static $bar;
static function init()
{
self::$bar = array(…);
}
}
Foo::init();
I have class DbTable, which implements all db queries to database such as insertRecord, updateRecord, ... But variable is not rewriting.
abstract class DbTable {
public static $table;
public static function insertRecord($data) {
// here I add some values to data, but that's not important
my_db::insert(self::$table, $data);
}
}
class User extends DbTable {
public static $table = 'table_users';
}
// everywhere I can call
User::insertRecord($data);
I know I can call
$c = get_called_class();
my_db::insert($c::$table, $data);
but I think that's not best solution at all.
Method and variables can be non static, I just use them because it is comfortable to write User::insertRecord instead of $user = new User(); $user->insertRecord($data);
When you're working with static classes you need to specify your variable source, in this case you're scoping to both classes and not on single class, this makes a difference, because self is scoping to concurrent class and when you want to scope for both classes you have to use static.
/**
* For testing
*/
class my_db {
public static function insert($table, $data){
echo $table;
}
}
abstract class DbTable {
public static $table = null;
public static function insertRecord($data) {
//self::$table is empty
//static::$table has 'table_users'
// here I add some values to data, but that's not important
my_db::insert(static::$table, $data);
}
}
class User extends DbTable {
public static $table = 'table_users';
}
// everywhere I can call
User::insertRecord(['Hi']);
self::$table is empty
static::$table has 'table_users'
You can read more about this here: SO Answer and PHP Documentation
Use static variables are unnecessary in this case. You just need dynamically create User object and them call method.
abstract class DbTable
{
protected $tableName;
public static function insertRecord($data)
{
$object = static::newInstance();
$object->insert($data);
}
public static function newInstance()
{
$className = get_called_class();
return new $className();
}
public function insert($data)
{
my_db::insert($this->tableName, $data);
}
}
class User extends DbTable
{
public function __construct()
{
$this->tableName = 'table_users';
}
}
You can now call:
User::insertRecord(['col1' => 'val1']);
But also you can insert rows from instated object:
$user = new User();
$user->insert(['col1' => 'val1']);
I have code similar to the following:
class ModuleRaceRegistration extends Module
{
protected $strTemplate = "template";
protected function compile()
{
// this doesn't work
$this->strTemplate = "template2";
}
}
From within the compile function I need to change the $strTemplate member. How can I do this?
Is an error being returned? Also, this might not be the case but compile is a protected method so you can only call it from within the class. If you are trying to call it from outside of the class, then it would need to be public.
Let me try
Example from manual
<?php
abstract class Base {
abstract protected function _test();
}
class Bar extends Base {
protected function _test() { }
public function TestFoo() {
$c = new Foo();
$c->_test();
}
}
class Foo extends Base {
protected function _test() {
echo 'Foo';
}
}
$bar = new Bar();
$bar->TestFoo(); // result: Foo
?>
I have a requirement where a process can be implemented in 2 different situation. One situation would be where the start date cannot be in the past and the other would be where it can.
Currently we utilise Value Objects where we perform a series of a validation items on each field submitted using Zend Validate objects.
The validation extends a base class e.g.
class ValueObject_test1 extends filter()
Filter is made up of: -
class filter {
protected $_filter;
protected $_filterRules = array();
protected $_validatorRules = array();
protected $_data = array();
protected $_objData = array();
protected $_options = array(Zend_Filter_Input::ESCAPE_FILTER => 'StripTags');
protected $_runValidation = true;
protected function _setFilter()
protected function _addFilter()
protected function _addValidator()
protected function _addData()
protected function _addObject()
protected function _addOption()
public function getData()
public function hasErrors()
public function getMessages()
public function getValidationState()
public function __get()
public function __isset()
public function __set()
}
ValueObject_test1 is made up of:
class ValueObject_test1 extends filter {
public function __construct($testVar) {
$this->_setData(testVar);
$this->_setFilters();
$this->_setValidators();
if($this->_runValidation) {
$this->_setFilter();
}
}
protected function _setFilters(){
$this->_addFilter("*", "StringTrim");
}
protected function _setData($testVar) {
$this->_addData('testVar', $testVar);
}
protected function _setValidators() {
$this->_addValidator('testVar', array(new Zend_Validate(), 'presence'=>'required', 'messages'=>'Enter something'));
}
}
What I'm trying to achieve is an extension of ValueObject_test1 so that my second situation will have an additional validation item as well as the items in ValueObject_test1()
I've written the following for my second situation:-
<?php
class ValueObject_test2 extends ValueObject_test1 {
public function __construct($testVar, $testVar2) {
$this->_setData($testVar, $testVar2);
$this->_setFilters();
$this->_setValidators();
if($this->_runValidation) {
$this->_setFilter();
}
}
protected function _setFilters(){
$this->_addFilter("*", "StringTrim");
}
protected function _setData($testVar, $testVar2) {
$this->_addData('testVar', $testVar);
$this->_addData('testVar2', $testVar2);
}
protected function _setValidators() {
$this->_addValidator('testVar2', array(new Zend_Validate(), 'presence'=>'required', 'messages'=>'Enter something'));
}
}
The issue i'm having is that the output from this only appears to validate my second situation validation and nothing on the second. I'm under the impression that by setting both variables in _setData() the validation should occur for items in ValueObject_test1 and the items in my ValueObject_test2?
class ValueObject_test2 extends ValueObject_test1 {
public function __construct($testVar, $testVar2) {
$this->_setData($testVar, $testVar2);
parent::__construct($testVar);
}
// _setFilters is identical to the parent implementation
protected function _setData($testVar, $testVar2) {
$this->_addData('testVar2', $testVar2);
parent::_setData($testVar);
}
protected function _setValidators() {
$this->_addValidator('testVar2', array(new Zend_Validate(), 'presence'=>'required', 'messages'=>'Enter something'));
parent::_setValidators();
}
}
My code doesn't call the _setData correctly because the $this->setData(testVar) inside the parent::_construct's will call the $this->_setData(testVar) version of the function.
If you want to override a function, your override will likely want to also run the logic of the parent.
<?php
class Foo {
protected function _setFoobar() {
// Foo logic
}
}
class Bar extends Foo {
protected function _setFoobar() {
// custom Bar logic specific to the child class (Bar)
parent::_setFoobar();
}
}