Jump to content

Slips

Members
  • Posts

    50
  • Joined

  • Last visited

    Never

About Slips

  • Birthday 05/11/1988

Profile Information

  • Gender
    Male
  • Location
    Bangalore, India

Slips's Achievements

Member

Member (2/5)

0

Reputation

  1. Hello all, My knowledge in PHP is growing everyday as I try out more stuff but I really didn't understand this bit : "Note: Please note that the ternary operator is a statement, and that it doesn't evaluate to a variable, but to the result of a statement. This is important to know if you want to return a variable by reference. The statement return $var == 42 ? $a : $b; in a return-by-reference function will therefore not work and a warning is issued in later PHP versions. ". taken from the page : http://www.php.net/manual/en/language.operators.comparison.php From what I understood, if I was to use a ternery condition in the return statement, and return a referenced variable as a result, it shouldn't work? So this shouldn't work? $int = 10; function testReturn(&$referencedVariable) { return (1==1) ? $referencedVariable : FALSE; } echo testReturn($int); But it does. Anyways i'm pretty sure I didn't understand this right, so help with this is really appreciated
  2. Thanks for all the advice everyone, but after doing some reading and , for my application design this seems about right to go with Classname::init();, a static defined method that will initialize all the necessary variables in that class. I will probably change my designs and learn more over time and as my application grows
  3. Hi guys, I am trying something fairly simple but I'm not sure if this would be a good practice. Basically I am using a big class called CommonLibrary that holds common functions as methods and common variables as static variables. But I have some variables here and there like $allAlphabet = range ('a' , 'z'), that cannot be declared as a property because it gives me a parse error. I don't want to call an object for this class because instancing it is of no use. Values will never change with regards to instances. So the next best thing that I tried was declaring all static variables first, and then changing thei property values inside the class __construct with self::$variable = 'somevalue', and then using this code below to assign values to the empty static variables. $dummyObject = new CommonLibrary; unset($dummyObject); echo CommonLibrary::$staticVariable; // This property is NULL before the constructer is triggered. Anyone recommend any better ways of doing this? Thanks in advance!
  4. Nevermind guys, after doing some testing I figured that it is not possible to read the files contents and start writing it from the beginning of the file , with the same file handler. All those options that allow reading and writing, at best will write only from the end of the file.
  5. Ok firstly I cannot use file_get_contents, because I want to read the file line by line and omit the lines I don't want. Using file_get_contents() with a regex to sniff those lines out seems more complex. Also file_get_contents is not preserving line breaks, something which I'll have to add manually. Basically what I'm trying to do, is remove entries for a web project on prompt from the /etc/hosts file. I was using file handlers because I can scan the file line by line and dump only the necessary entries into a new variable and omit the unwanted entries. This 'new' config will then overwrite the previous hosts file. Here is what my code must do : Create new variable that will hold the new overwriting config Open hosts file Scan entires in it line by line and dump lines that are needed into the variable we created Overwrite the old config text with the new config txt in the variable with fwrite()
  6. Hello all, I'm trying to open a file, take some text from it conditionally, and paste the newly edited text back into the same file. At first I used a seperate fopen($handle, 'r') handler to open the file to read it, get its contents CONDITIONALLY, close the read handler, and open a new write handler to overwrite the file. In short, I need to extract the text from the file after ignoring some amount of text , and then rewrite the file with the newly altered text. I was trying out r+ and w+ options when using fopen(), but w+ is working in a way thats leaving me confused. Here is my code. $file = 'test.txt'; $fileHandle = fopen($file,'w+'); fwrite($fileHandle, 'Newly inserted text'); $fileContents = fread($fileHandle, filesize($file)); echo $fileContents; fclose($fileHandle); The manual says that if the w+ option is specified then the file is opened for reading and writing. From what I understand this means that I should be able to read from the file after writing to it. But the code above displays nothing after writing to the file. The file is chmodded 777. Can someone please explain to me why this is so Thanks
  7. Yep, I finally settled for passing arguments. And i did use if (function_exists... The main reason I wanted to do it that way was to make sure there is as less dependent code as possible (i.e have to change the arguments if the parent arguments change in future, and the code was using around 5-7 arguments)
  8. Ah damn, but anyways I was doing it this way because the child function was needed to repeat some actions in the parent function code and it seemed like the only way I know, from my knowledge(and it isn't a lot lol). My other choice was to use goto: but I've read a bit about how goto can create some bad spaghetti code..
  9. Hello all, I have some piece of code that is nested like this $variable = 'This is a global argument'; function parentFunction($variable) { function childFunction() { echo 'Argument of the parent function is '.$GLOBALS['variable']; } childFunction(); } parentFunction(5); What I want to know is - Is there a way to access a variable from the parent function without passing arguments to the child function? (Something like how classes have parent::?). I don't want to use $GLOBALS because it might cause some variable collision, and I didn't want to pass arguments because incase I decide to change the arguments in the parent function I'd have to do it in the child function aswell. From my searching around in the Internet it seems like this is not possible, but if theres a slight chance that there might be something out there, i'm willing to give it a shot . Thanks in advance
  10. Hmmm all variables seem fine on my checking but here is the full code anyways. The script is incomplete, but with regards to creating a working HTTP config file i guess this is all that is needed for now : Don't worry about the include file, its called because it contains a function that converts a text into camelcaps. Here is a quick overview of the logic so you guys can understand this code quicker : 1. Run script in command prompt 2. Ask user for Full project name. User types something like "PHP Freaks" 3. Ask user for short project name. User types something like "phpf" (Needed for naming directories) 4. Start a foreach loop that asks user if they want a separate domain for css,jss,images files. If user types 'y' - use sprintf, and replace the customize the vhost config text (<Virtual Host:*80> ... </Virtual Host>) with the respective subdomain name, and concantenate it to the final config text , inside each iteration. 5. Looping and concatenation done, final config text is ready to paste with the vhost config text for 3x subdomains. Open a file and write to it. include '/var/www/common/lib/functions/all.php'; // Ask for the Project full name and short name (Needed for naming conventions for files and directories etc.) fwrite(STDOUT,'Enter the full name of the Web Project please :'); $fullProjectName = fgets(STDIN); fwrite(STDOUT, "Enter the short name for the project please : "); $shortProjectName = fgets(STDIN); $projectAliases = array($shortProjectName => $fullProjectName); // 1. Create a new File in sites-available folder. $sitesAvailableFolder = '/etc/apache2/sites-available'; $httpConfigFile = $sitesAvailableFolder.'/'.convertToCamelCaps($projectAliases[$shortProjectName], TRUE); if(!is_file(trim($httpConfigFile))) { //HTTP config file does not exist, lets begin creating the config text echo 'HTTP Config file ', $httpConfigFile, 'not found, please follow the instructions below to create one.', PHP_EOL; $subDomainList = array('css', 'jss', 'images'); // In the foreach loop below , using a $variable.= in the first iteration gives an error because it has nothing to concatenate to, // so I created 2 empty variables to concatenate to, anyone know any better ways of doing this? $subDomainConfig = ''; $httpConfigFileText = ''; foreach ($subDomainList as $index => $subDomain) { fwrite(STDOUT, 'Would you like to add a subdomain for ' .ucwords($subDomain). ' files?'); ${$subDomain.'Install'} = fgets(STDIN); if (trim(${$subDomain.'Install'}) == 'y') { $subDomainConfig .= ' <VirtualHost *:80> ServerAdmin webmaster@%2$s ServerName %1$s.%2$s ServerAlias %1$s.%2$s # Indexes + Directory Root. DirectoryIndex index.html index.php DocumentRoot /var/www/%2$s/public_html/ # CGI Directory ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/ <Location /cgi-bin> Options +ExecCGI </Location> # Logfiles ErrorLog /var/www/%2$s/logs/apache/error.log CustomLog /var/www/%2$s/logs/apache/access.log combined </VirtualHost> '.PHP_EOL; $httpConfigFileText.= sprintf($subDomainConfig, $subDomain, $shortProjectName); } } // Take the contenated config text and write it to the file. try { if ($fileHandle = @fopen($httpConfigFile, 'w')) { if (!fwrite($fileHandle, $httpConfigFileText)) { throw new Exception('Failed to write the Virtual host configuration for '.$fullProjectName); } else { echo 'The HTTP Config file was successfully created.', PHP_EOL; } } else { throw new Exception('Failed to create the HTTP Config file '.$httpConfigFile); } } catch (Exception $e) { echo 'Exception caught : ', $e->getMessage(); } } else { echo 'The file, ', $httpConfigFile, 'already exists.', PHP_EOL; }
  11. Hello all, I am trying to create a PHP CLi Script that will help me setup new config and server files / directories for every new web project i get instead of me having to manually create everything with each project. The script accepts the project name, and y/n for whether i want to create subdomains for css, jss and image files. After it has that, it must create a new http config file under sites-available (in Linux), by pasting the config file text. Problem : If I output regular text to the file, it displays exactly in the format that I write the string variable. But when I use a printf, or try to use variables directly in the config text, it starts formatting the text in the config file in a strange way. I just want the variables to just be replaced and the text to appear in the exact format below. The text displays perfectly as i typed below in the config file if I don't use any variables. $subDomainConfig .= '<VirtualHost *:80> ServerAdmin webmaster@%1$s ServerName %1$s.%2$s ServerAlias %1$s.%2$s # Indexes + Directory Root. DirectoryIndex index.html index.php DocumentRoot /var/www/%2$s/public_html/ # CGI Directory ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/ <Location /cgi-bin> Options +ExecCGI </Location> # Logfiles ErrorLog /var/www/%2$s/logs/apache/error.log CustomLog /var/www/%2$s/logs/apache/access.log combined </VirtualHost> '.PHP_EOL; $httpConfigFileText = sprintf($subDomainConfig, $subDomain, $shortProjectName); The above code outputs text in this way in the file : <VirtualHost *:80> ServerAdmin webmaster@images ServerName images.mysite ServerAlias images.mysite # Indexes + Directory Root. DirectoryIndex index.html index.php DocumentRoot /var/www/mysite /public_html/ # CGI Directory ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/ <Location /cgi-bin> Options +ExecCGI </Location> # Logfiles ErrorLog /var/www/mysite /logs/apache/error.log CustomLog /var/www/mysite /logs/apache/access.log combined </VirtualHost>
  12. I tried (string) before the argument name and I got this error : PHP Parse error: syntax error, unexpected T_STRING_CAST, expecting '&' or T_VARIABLE in ... Had no idea PHP's type specifying was weak. Thought i'd make my code more solid by doing this in all my functions if this one worked. Oh well, guess i'll just do it inside the function. Thanks for the tip.
  13. Hello all, I just created this function that I want to use in CLi mode. It works perfectly in regular browser mode, but gives me this error on Cli mode if I do convertToCamelCaps('TEST STRING'); PHP Catchable fatal error: Argument 1 passed to convertToCamelCaps() must be an instance of string, string given in file... if (!function_exists('convertToCamelCaps')) { function convertToCamelCaps(string $string, $initialCaps=FALSE) { if ($words = explode(' ',$string)) { foreach ($words as $index => &$word) { $word = strtolower($word); if($index==0 && $initialCaps===FALSE) { continue; } $word = ucwords($word); } return implode('',$words); } return FALSE; } } If I remove the string datatype requirement in the function before the function argument list, it works fine in CLi mode.
  14. I see, that explains all those times my spaces wouldn't display, thanks a lot for clearing that up.
  15. Wow, all three ways you suggested worked great, but it doesn't seem to preserve the spaces when in text/html. Is this normal? I tried the same code on chrome as well, and got the same results (Padding was eaten away).
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.